Out of two lists: listA and listB, I want to remove all entries of listB from listA based on some condition.
Now when I try .Except
, I am not getting desired result.
// This comes with listA
var usingExcept = listA.Except(listB).ToList();
But when I try .RemoveAll
then I get desired result.
listA.RemoveAll(x => listB.Exists(y => y.OperationId == x.OperationId));
How to leverage .Except
here, if possible?
.Net Fiddle with example.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var listA = new List<MyObject>{new()
{OperationId = 123, Mode = "In-Transit", Location = "ATL", }, new()
{OperationId = 234, Mode = "Delivered", Location = "PHX", }, new()
{OperationId = 345, Mode = "Delivered", Location = "COL", }};
var listB = new List<MyObject>{new()
{OperationId = 123, Mode = "In-Transit", Location = "ATL", }};
var usingExcept = listA.Except(listB);
Console.WriteLine(usingExcept.Count());
listA.RemoveAll(x => listB.Exists(y => y.OperationId == x.OperationId));
Console.WriteLine(usingExcept.Count());
}
}
public class MyObject
{
public int OperationId { get; set; }
public string Mode { get; set; }
public string Location { get; set; }
}