简体   繁体   中英

Copy distinct id's to a list

I have 4 Lists, like this:

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?

You'll need MoreLinq for the DistinctBy :

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

for just the Id's :

 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?

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:

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:

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 :

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.

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.

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