0

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?

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Martin
  • 219
  • 1
  • 10
  • 1
    did you search for "how to convert a string to an int"? There are dozenzs of similar questions, e.g. https://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int – MakePeaceGreatAgain Jan 26 '22 at 16:07

3 Answers3

1

try this

var myNewList = items.Where(p => myIds.Contains( p.id.ToString)).ToList();
Serge
  • 40,935
  • 4
  • 18
  • 45
1

There are two problems:

  1. You are trying to compare int values with string values. Either convert the strings to ints or the ints to strings. I suggest convert the int ids to string as this always works, where as converting a string to an int could fail.
  2. You are trying to use an id of myIds to index myIds. This is redundant, since the id p2 is already an element of myIds.
var myNewList = items
   .Where(p => myIds.Any(p2 => p2 == p.id.ToString()));
                               ^               ^
//    Use p2 instead of myIds[p2]      Convert int to string
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0

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()); 
Amjad S.
  • 1,196
  • 1
  • 4
  • 16