Home > Software design >  return items that matches the list in linq
return items that matches the list in linq

Time:11-12

I have a list of objects with this properties:

name    “James" 
Country "Austrálie" 
Age 32

I have another list of object called person that contains names “james”, “Max”…….

So let's say I have one list called MyListOfObjects that contains name,Country,Age and a list of objects called person that contains name property.

I want to return in Linq all the objects Name and country that match the other list names in person object .

so I was trying to do something like var bb = MyListOfObjects.Where(b => persons.All(a => b.Name.Equals(a.Name))).ToList();

brings 0 results

while if I try var desiredObjects = b.Table.Rows.Where(x => persons.Contains(x.Name)).ToList(); gives error as it can t convert

    private static IEnumerable<Person> persons = new[]
    {Name = “James”,Name = “Jimmy"}

Any help?

CodePudding user response:

Use .Where() extenstion of Linq to filter through your objects list.Its similar to what you have already tried.

var desiredObjects = MyListOfObjects.Where(x => names.Contains(x.Name)).ToList();

  • Related