Sid M
Sid M

Reputation: 4354

Remove unmatched records from list

I have a class ABC like this

public class ABC{
public int Id {get;set;}
public int UserCount {get;set;}
}

Now I add following records to a list of type ABC

List<ABC> lstABC = new List<ABC>();
lstABC.Add(new ABC(){Id=1,UserCount=5});
lstABC.Add(new ABC(){Id=2,UserCount=15});
lstABC.Add(new ABC(){Id=3,UserCount=3});
lstABC.Add(new ABC(){Id=4,UserCount=20});
lstABC.Add(new ABC(){Id=5,UserCount=33});
lstABC.Add(new ABC(){Id=6,UserCount=21});

I've another list of type int

List<int> lstIds = new List<int>();
lstIds.Add(1);
lstIds.Add(3);
lstIds.Add(4);

Now i want to remove all the items from lstABC whose Id's do not match in lstIds without using any loops. What is the most optimized way to do this?

Upvotes: 1

Views: 1032

Answers (3)

Rohit
Rohit

Reputation: 10236

Another solution somewhat simpler to read

  lstABC = (from l in lstABC
                 where lstIds.Contains(l.Id)
                 select l).ToList();

Instead of removing you can also select only the matching elements

Upvotes: 0

ShloEmi
ShloEmi

Reputation: 1984

Continuing @Coder1409 solution, use HashSet to boost performance (for big collections):

HashSet<int> hashSet = new HashSet<int>(lstIds);
lstABC.RemoveAll(x => !hashSet.Contains(x.Id));

HTH

Upvotes: 0

Coder1409
Coder1409

Reputation: 498

you can just use RemoveAll like this :

lstABC.RemoveAll(x => !lstIds.Contains(x.Id));

it should work easily

Upvotes: 2

Related Questions