简体   繁体   中英

If a list of object has matching elements from another list

I have a list of strings

List<string> listOfStrings = {"1","2","3","4"};

And I have a list of objects which looks like this

class Object A{
    string id;
    string Name;
}

How can I find all the objects which has matching list of strings.

I tried:

listOfA.Where(x => listoFstrings.Contains(x.id)).Select();

But it is not working, it is pulling all the other objects which doesn't have a matching string.

Here's a compilable, working version of your code:

// Specify list of strings to match against Id
var listOfStrings = new List<string> { "1", "2", "3", "4" };

// Your "A" class
public class A
{
    public string Id { get; set; }
    public string Name { get; set; }
}

// A new list of A objects with some Ids that will match
var listOfA = new List<A> 
{
    new A { Id = "2", Name = "A-2" },
    new A { Id = "4", Name = "A-4" },
};

Now you should be able to just about use your original code, except instead of .Select() I've used .ToList() :

// Search for A objects in the list where the Id is part of your string list
var matches = listOfA.Where(x => listOfstrings.Contains(x.Id)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM