Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate Dictionary using LINQ?

public class Person
{
     public string Email {get; set;}
     public string Name {get; set;}
}

public Report : Dictionary<string, string>
{
     public Report()
     {
         List<Person> list = getData(); // filled with Person's
         var realList = list.Where(x => x.Name != "test");
         foreach( var i in realList)
         {
              this.Add(i.Email,i.Name);
         }
     }

}

I tried to simplify my code to get down to the question. Basically I have a list of Persons and I want to get a sub list of that and then for each element in the sub list I want to add it to this dictionary which is the class.

My question: Is there a way to get rid of that foreach statement and achieve the same effect with in the linq statement above. Because it seems silly to me to go through the list once and then through the sub list. So what would be good if during the linq statement if x.Name is not equal to test then it adds it to the dictionary.

like image 522
Beastwood Avatar asked Dec 05 '22 06:12

Beastwood


1 Answers

My question: Is there a way to get rid of that foreach statement and achieve the same effect with in the linq statement above. Because it seems silly to me to go through the list twice

You don't go through the list twice in your code - the list is only enumerated once, as LINQ uses deferred execution. This is likely the best way to achieve this.

If you didn't subclass a dictionary, however, and encapsulated one instead, you could use ToDictionary to create the encapsulated dictionary:

List<Person> list = getData(); // filled with Person's
Dictionary<string,string> people = list
                                     .Where(x => x.Name != "test")
                                     .ToDictionary(x => x.Email, x => x.Name);
like image 67
Reed Copsey Avatar answered Dec 16 '22 23:12

Reed Copsey