'Get elements from list whose ids are in another
I'm new to C# and I ran into a problem.
I have a custom list of lists of my custom type :
items = [
{
id = 1,
...
},
{
id = 2,
...
},
...
]
And another list that contains only ids and is a list of strings:
myIds = ["1", "2", "3", ...]
I need to get those elements from items whose ids are in myIds.
How to perform that in a good way as I tried:
var myNewList = items.Where(p => myIds.Any(p2 => myIds[p2] == p.id));
But there is error that string cannont be converted to int?
Solution 1:[1]
try this
var myNewList = items.Where(p => myIds.Contains( p.id.ToString)).ToList();
Solution 2:[2]
the issue is be because you are comparing int Type with string Type. Try this:
var myNewList = items.Where(p => myIds.Any(p2 => p2 == p.id.ToString());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge |
| Solution 2 |
