简体   繁体   English

将不同的ID复制到列表中

[英]Copy distinct id's to a list

I have 4 Lists, like this: 我有4个列表,像这样:

List <Emp> l1 = new List<Emp>();
List <Emp> l2 = new List<Emp>();
List <Emp> l3 = new List<Emp>();
List <Emp> l4 = new List<Emp>();

Emp has a property called id , How can I get a List of all distinct id's present in all the four Lists? Emp有一个名为id的属性,如何获得所有四个列表中所有不同id的列表?

You'll need MoreLinq for the DistinctBy : 你需要MoreLinq为DistinctBy:

 IEnumrable<Emp> uniqueEmps = l1.Concat(l2).Concat(l3).Concat(l4)
                                .DistinctBy(e => e.id);

for just the Id's : 对于Id的:

 IEnumrable<int> uniqueIds = l1.Concat(l2).Concat(l3).Concat(l4)
                               .Select(e => e.id).Distinct();

How can I get a List of all distinct id's present in all the four Lists? 如何获得所有四个列表中所有不同ID的列表?

If you are looking for a list of IDs (as opposed to Emp objects that have these IDs) you can do it with a simple query: 如果要查找ID列表(而不是具有这些ID的Emp对象),可以使用简单查询来完成:

var ids = l1.Concat(l2).Concat(l3).Concat(l4).Select(e => e.Id).Distinct();

If your emp class implements equality comparison then you can just union the lists together: 如果你的emp类实现了相等比较,那么你可以将列表组合在一起:

IEnumrable<int> uniqueIds = l1.Union(l2).Union(l3).Union(l4).Select(e => e.id);

To implement equality in your class, you simply override Equals and GetHashCode : 要在类中实现相等性,只需重写EqualsGetHashCode

public override bool Equals(object obj)
{
    var compareTo = obj as Emp;
    return Id.Equals(CompareTo.Id);
}

public override int GetHashCode()
{
    return Id.GetHashCode();
}

The benefit of doing it this way is that anywhere you need to compare two emp instances, it will leverage this implementation. 这样做的好处是,无论您需要比较两个emp实例,它都会利用此实现。

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

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