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>
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();
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();
使用Distinct扩展方法将返回一个IEnumerable,然后您可以在其上执行ToList()
:
List<Person> plst = cl.PersonList.Distinct().ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.