c# - LINQ's Distinct() on a particular property -


I'm playing with LINQ to learn about it, but I do not know when I do not have a simple list (Making a simple list of integers is very easy, this is not a question). What do I want on the list of an object on one or more properties of objects?

Example: If an object person , with property ID . How can I get the object's property with id and use distinct on them?

Person1: Id = 1, name = "Test1" Person2: Id = 1, name = "Test1" Person3: Id = 2, name = "Test2"

How can I get only the person 1 and person 3? Is this possible?

If this is not possible with LINQ, what would be the best way to create a list of person based on some of its properties? 3.5.

Edit : This is now part of the

Do you really need a "different" I do not believe that it is part of LINQ because it stands, though it is quite easy to write:

  Public Stable IEnumerable & lt; TSource & gt; Different types of & lt; TSource, TKey & gt; (This IEnumerable & lt; TSource & gt; source, function & lt; TSource, TKey & gt; key selector) {HashSet & lt; TKey & gt; Scenes = NewHashet & lt; TKey & gt; (); Foreign currency (tsos element in source) {if seen (pair. (Key selector (element)) {yield returns element; }  

To get different values ​​using only the id property, you can use it:

 < Code> var query = People.Distinct By (p = & gt; p.Id);  

And to use many properties, you can use anonymous forms, which implement equality properly:

  var Query = people.DistinctBy (p = & gt; new {PID, P. name}}  

unchecked, but this should work (and now at least compiled).

This assumes the default comparison for the key - although you compare the similarity, simply pass it to the hashset constructor.


Comments