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 :
There are two problems:
- You are trying to compare
intvalues withstringvalues. Either convert the strings to ints or the ints to strings. I suggest convert theintids tostringas this always works, where as converting astringto anintcould fail. - You are trying to use an id of
myIdsto indexmyIds. This is redundant, since the idp2is already an element ofmyIds.
var myNewList = items
.Where(p => myIds.Any(p2 => p2 == p.id.ToString()));
^ ^
// Use p2 instead of myIds[p2] Convert int to string