Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ using C# question

Tags:

c#

linq

I have a List<T> that contains some user defined class data.

I want to find the unique instances of a combination of 2 data fields.

For example, if the entries contain the fields Name and Age, I want the unique cases of the Name and Age combination, e.g. Darren 32, should only be retrieved once, even if it is in the list multiple times.

Can this be achieved with LINQ?

Thanks.

like image 728
Darren Young Avatar asked Feb 04 '11 10:02

Darren Young


2 Answers

You need to extract only these data fields and make them unique:

var result = list
  .Select(x => new { Age = a.Age, Name = x.Name})
  .Distinct();

This creates a IEnumerable of a anonymous type which contains a Age and Name property.

If you need to find the items behind the unique data, you need GroupBy. This will provide the list with the single items behind each group.

var result = list
  .GroupBy(x => new { Age = a.Age, Name = x.Name});

foreach (var uniqueItem in result )
{
    var age = uniqueItem.Key.Age;
    var name = uniqueItem.Key.Name;
    foreach (var item in uniqueItem)
    {
       //item is a single item which is part of the group
    }
}
like image 50
Stefan Steinegger Avatar answered Oct 05 '22 03:10

Stefan Steinegger


myList.Select(l => new { l.Name, l.Age })
      .Distinct()
      .ToDictionary(x => x.Name, x => x.Age)
like image 30
Kris Ivanov Avatar answered Oct 05 '22 03:10

Kris Ivanov