How to Compare two Generic List one contain int and another contain class object

StackOverflow https://stackoverflow.com/questions/19813436

  •  04-07-2022
  •  | 
  •  

Question

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

Était-ce utile?

La solution

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;  

Autres conseils

Try this:

GetTransData.Where(gtd => _GetRecCust.Any(grc => grc == int.Parse(gtd.Id))).ToList();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top