LINQ using C # question

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

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

For example, if the records contain the Name and Age fields, I need unique cases of the combination of Name and Age, for example. Darren 32 should only be retrieved once, even if it is listed several times.

Can this be done with LINQ?

Thanks.

+4
source share
5 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 an IEnumerable of an anonymous type that contains the Age and Name property.

If you need to find elements for unique data, you need GroupBy . This will provide a list of individual items for 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 } } 
+5
source
 myList.Select(l => new { l.Name, l.Age }) .Distinct() .ToDictionary(x => x.Name, x => x.Age) 
+4
source

You need to write your own equality resolver and use Linq. Great feature .

+3
source

Look at the Distinct extension method

+1
source

Easy:

 var people = new List<Person>(); // code to populate people var uniqueNameAges = (from p in people select new { p.Name, p.Age }).Distinct(); 

And then into the dictionary:

 var dictionary = uniqueNameAges .ToDictionary(x => x.Name, x => x.Age); 

Or for a search (very similar to Dictionary<string, IEnumerable<int>> in this case):

 var lookup = uniqueNameAges .ToLookup(x => x.Name, x => x.Age); 

If you have people with the name "John" with different ages, you can access them like this:

 IEnumerable<int> ages = lookup["John"]; 
+1
source

Source: https://habr.com/ru/post/1338407/


All Articles