繁体   English   中英

如何从列表中获取不同的数据?

[英]How to get the distinct data from a list?

我希望从人员名单中获得不同的清单。

List<Person> plst = cl.PersonList;

如何通过LINQ做到这一点。 我想将结果存储在List<Person>

Distinct()将为您提供不同的值 - 但除非您重写Equals / GetHashCode()否则您将获得不同的引用 例如,如果您希望两个Person对象在名称相等时相等,则需要重写Equals / GetHashCode来指示。 (理想情况下,实现IEquatable<Person>以及重写Equals(object) 。)

然后,您需要调用ToList()List<Person>返回结果:

var distinct = plst.Distinct().ToList();

如果你想通过某些特定属性获得不同的人,但这不是“自然”平等的合适候选者,你需要像这样使用GroupBy

var people = plst.GroupBy(p => p.Name)
                 .Select(g => g.First())
                 .ToList();

或使用MoreLINQ中DistinctBy方法:

var people = plst.DistinctBy(p => p.Name).ToList();

您可以使用Distinct方法,您将需要实现IEquatable并覆盖equals和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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM