0

How to compare these two Generic list and get the matching data as per ID

List<int> _GetRecCust;
List<Tranobject> GetTransDeta;

I tried

var TransactionsToProcess = GetTransDeta.Where(x => _GetRecCust.Contains(Convert.ToInt32(x.ID)));

but not able to get a comman ID data.

Both having ID as a field.

Thanks in advance

Rahul
  • 5,603
  • 6
  • 34
  • 57

2 Answers2

5

The most efficient approach is using Enumerable.Join:

var common = from x in GetTransDeta
             join id in _GetRecCust
             on int.Parse(x.Id) equals id
             select id;
List<int> commonIDs = common.ToList();

By the way, why is Tranobject.Id a string at all?

Edit: Since you have commented that there are nulls, you could use IsNullOrWhiteSpace first:

var common = from x in GetTransDeta
             where !string.IsNullOrWhiteSpace(x.Id)
             join id in _GetRecCust
             on int.Parse(x.Id) equals id
             select id;  
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • thanks for ur rply what i am getting `Input string was not in a correct format..` – Rahul Nov 06 '13 at 13:48
  • @Rahul: Probably because an `Id` was not convertible to `int`, is that possible? Do you have empty strings, `null` or white-spaces? – Tim Schmelter Nov 06 '13 at 13:51
  • yes in some cases i have null as well.how to apply condition for null check – Rahul Nov 06 '13 at 13:56
  • @Rahul: What do you want to do with these nulls, just skip them or link with an `id=0`? – Tim Schmelter Nov 06 '13 at 13:57
  • i don't want to use null values but can i check for null as well in the same query or assign `0` to null. – Rahul Nov 06 '13 at 14:00
  • @Rahul: I have edited my answer to show how to ignore these `null`(or white-space) values. You could also modify the join: `on int.Parse(x.Id ?? "0") equals id`. – Tim Schmelter Nov 06 '13 at 14:02
2

Try this:

GetTransData.Where(gtd => _GetRecCust.Any(grc => grc == int.Parse(gtd.Id))).ToList();
gleng
  • 6,185
  • 4
  • 21
  • 35