Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if elements from one list elements present in another list

I have 2 c# classes –

class ABC
{
  string LogId;
  string Name;
}

class XYZ
{
  string LogId;
  string Name;
}

class Checker
{
  public void comparelists()
  {
    List<ABC> lstABC =new List<ABC>();
    lstABC.Add(new ABC...);
    lstABC.Add(new ABC...);
    lstABC.Add(new ABC...);

    List<XYZ> lstXYZ =new List<XYZ>();
    lstXYZ.Add(new XYZ...);
    lstXYZ.Add(new XYZ...);
    lstXYZ.Add(new XYZ...);

    var commonLogId = lstABC
      .Where(x => lstXYZ.All(y => y.LogId.Contains(x.LogId)))
      .ToList();


  }
}

As seen from the code , I want to fetch all logids from lstABC which are present in lstXYZ.

Eg. lstABC has ->

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

LogId="1", Name="somename1"
LogId="2", Name="somename2"
LogId="3", Name="somename3"
LogId="4", Name="somename4"
LogId="5", Name="somename5"

lstXYZ has ->

LogId="1", Name="somename11"
LogId="2", Name="somename22"
LogId="3", Name="somename33"
LogId="8", Name="somename8"
LogId="9", Name="somename9"

Then all logids from lstABC which are present in lstXYZ are – 1,2,3 ; so all those records are expected to get fetched.

But with below linq query –

var commonLogId = lstABC
  .Where(x => lstXYZ.All(y => y.LogId.Contains(x.LogId)))
  .ToList();

0 records are getting fetched/selected.

>Solution :

approach with Any()

var res = lstABC.Where(x => (lstXYZ.Any(y => y.LogId == x.LogId))).Select(x => x.LogId);

https://dotnetfiddle.net/jRnUwS


another approach would be Intersect() which felt a bit more natural to me

var res = lstABC.Select(x => x.LogId).Intersect(lstXYZ.Select(y => y.LogId));

https://dotnetfiddle.net/7iWYDO

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading