Reputation: 11423
I want to get distinct list from list of persons .
List<Person> plst = cl.PersonList;
How to do this through LINQ
. I want to store the result in List<Person>
Upvotes: 3
Views: 389
Reputation: 148180
You can use Distinct method, you will need to Implement IEquatable and override equals and hashcode.
public class Person : IEquatable<Person>
{
public string Name { get; set; }
public int Code { get; set; }
public bool Equals(Person other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;
//Check whether the person' properties are equal.
return Code.Equals(other.Code) && Name.Equals(other.Name);
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public override int GetHashCode()
{
//Get hash code for the Name field if it is not null.
int hashPersonName = Name == null ? 0 : Name.GetHashCode();
//Get hash code for the Code field.
int hashPersonCode = Code.GetHashCode();
//Calculate the hash code for the person.
return hashPersonName ^ hashPersonCode;
}
}
var distinctPersons = plst.Distinct().ToList();
Upvotes: 1
Reputation: 49985
Using the Distinct extension method will return an IEnumerable which you can then do a ToList()
on:
List<Person> plst = cl.PersonList.Distinct().ToList();
Upvotes: 1
Reputation: 1503290
Distinct()
will give you distinct values - but unless you've overridden Equals
/ GetHashCode()
you'll just get distinct references. For example, if you want two Person
objects to be equal if their names are equal, you need to override Equals
/GetHashCode
to indicate that. (Ideally, implement IEquatable<Person>
as well as just overriding Equals(object)
.)
You'll then need to call ToList()
to get the results back as a List<Person>
:
var distinct = plst.Distinct().ToList();
If you want to get distinct people by some specific property but that's not a suitable candidate for "natural" equality, you'll either need to use GroupBy
like this:
var people = plst.GroupBy(p => p.Name)
.Select(g => g.First())
.ToList();
or use the DistinctBy
method from MoreLINQ:
var people = plst.DistinctBy(p => p.Name).ToList();
Upvotes: 5