Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

c# - LINQ compare two lists and remove

I have two lists. I want to remove any items from LIST1 that are NOT present in LIST2.

So for example:

        var list1 = new List<DownloadTask>();
        list1.Add(new DownloadTask{ OperationID = 1, MachineID = 1 });
        list1.Add(new DownloadTask{ OperationID = 2, MachineID = 1 });
        list1.Add(new DownloadTask{ OperationID = 3, MachineID = 1 });
        list1.Add(new DownloadTask{ OperationID = 3, MachineID = 2 });

        var list2 = new List<DownloadTask>();
        list2.Add(new DownloadTask{ OperationID = 1, MachineID = 1 });
        list2.Add(new DownloadTask{ OperationID = 3, MachineID = 2 });

After run list1 should contain only items: with combination operationId = 1, machineId = 1 AND OperationId = 3, MachineId =2.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think it should be:

list1.RemoveAll(x => list2.Exists(y => y.OperationID == x.OperationID && y.MachineID == x.MachineID));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...