xVice1337
xVice1337

Reputation: 7

LINQ Problem takes all from list not the ones i want

Hey so im still working on my project and i ran into another problem, its kinda hard to explain but i think my LINQ might just be wrong:

        private async void AddTasks()
        {
            List<string> folders = new List<string>();
            List<TaskStruct> allTasks = await taskApi.GetTasks();
            flowLayoutPanel2.Controls.Clear();
            foreach (TaskStruct task in allTasks)
            {
                if (folders.Contains(task.folder) == false)
                {
                    folders.Add(task.folder);
                    var newFolder = new TaskFolderView(this, task.folder, allTasks.Where(task => task.folder.Equals(task.folder)).ToList());
                    flowLayoutPanel2.Controls.Add(newFolder);
                }
            }
        }

I think the problem is on:

var newFolder = new TaskFolderView(this, task.folder, allTasks.Where(task => task.folder.Equals(task.folder)).ToList());

I get allTasks in the view like this but i only want the ones that match with the foldername. Hope someone can help

Upvotes: -1

Views: 41

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

The problem is that you have used the same variable name twice. You use it once here:

foreach (TaskStruct task in allTasks)

and again here:

Where(task =>

Look at the condition in your Where call:

task.folder.Equals(task.folder)

Why would you think that you could use task.folder twice in the same expression and have it mean two different things? Both of those are referring to the inner task variable so you're just equating one thing with itself, which is always true, which is why every item matches.

This is an example of why I always use type initials for LINQ range variables in this context. They will never clash with other variables and the scope is so small that there's never a risk of their being confusing. You can do this:

Where(t => t.folder.Equals(task.folder))

and now you're actually equating two different things.

Upvotes: 1

Related Questions