How to get the distinct data from a list?

最后都变了- 提交于 2019-12-30 10:52:32

问题


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>


回答1:


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();



回答2:


Using the Distinct extension method will return an IEnumerable which you can then do a ToList() on:

List<Person> plst = cl.PersonList.Distinct().ToList();



回答3:


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();


来源:https://stackoverflow.com/questions/13438673/how-to-get-the-distinct-data-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!