34

I have a list of objects with three integer properties. How can I get the distinct values of first integer property from my list?

0

4 Answers 4

78

This should work,

List<int> result = YourListObject.Select(o => o.FirstInteger).Distinct().ToList();
1
  • 1
    +1 List<int> result = YourListObject.Select(o => o.FirstInteger).AsParallel().Distinct().ToList() "AsParallel()" might give some performance benfit, if we doesn't care about order and have more items in the list.
    – Sai
    Oct 22, 2015 at 20:56
11

Try:

var g = collection.Select(i => i.Property1).Distinct();

Could you post some source code so that we can give you a better example?

EDIT:

In my example, I have a collection collection which contains numerous instances of your class. I'm then selecting Property1 from each class, filtering to the distinct values of that property.

8

I have found this useful and working fine for me for strings.

var distinctNames = (from d in YourList select d).Distinct();

Hope this is useful for some one like me searching for details in SO.

3

Example of a more complex distinct'ing....

licenseLookupItems = tmpList
                .GroupBy(x => new {x.LicenseNumber, x.Name, x.Location, x.Active, x.Archived})
                .Select(p => p.FirstOrDefault())
                .Select(p => new LicenseNumberLookupItem
                {
                    LicenseNumber = p.LicenseNumber,
                    Name = p.Name,
                    Location = p.Location,
                    Active = p.Active,
                    Archived = p.Archived
                })
                .ToList();
1
  • Nice to pull multiple distinct parts of a record
    – DRapp
    Apr 21, 2019 at 23:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.