How can I write this example more succinctly in LINQ?

From this list

List<Foo> list = new List<Foo>()
{
  new Foo("Albert", 49, 8),
  new Foo("Barbara", 153, 45),
  new Foo("Albert", -23, 55)
};

      

I want to get a dictionary with names as a key and the first Foo

-object from a list with a given name as a value.

Is there a way to write logic more succinctly using LINQ than what I've done here?

Dictionary<string, Foo> fooByName = new Dictionary<string, Foo>();

foreach (var a in assignmentIndetifiers)
{
  if (!names.ContainsKey(a.ValueText))
  {
    names.Add(a.ValueText, a);
  }
}

      

+3


source to share


2 answers


You can try something like this:

var dictionary = list.GroupBy(f=>f.Name)
                     .Select(gr=>new { Name = gr.Key, Foo = gr.First() })
                     .ToDictionary(x=>x.Name, x=>x.Foo);

      

My guess is that it Foo

has a property Name

that you want to use as a key for your dictionary. If this is not the case, you should change it accordingly.

Essentially we are grouping the elements found in list

the base Name

and then we project the result onto the anonymous type of two properties: Name

and Foo

, which appear to be associated with the key / value of the required diction, and then we call the method ToDictionary

.



Update

As Igor correctly pointed out, you can pass the entire projection with Select

and immediately callToDictionary

var dictionary = list.GroupBy(f=>f.Name)
                     .ToDictionary(gr=>gr.Key, gr=>gr.First());

      

+11


source


Alternatively, GroupBy()

you can use MoreLinqDistinctBy()

(available via NuGet):



var names = items.DistinctBy(x => x.ValueText).ToDictionary(x => x.ValueText);

      

0


source







All Articles