Home > Software engineering >  Get elements from list whose ids are in another
Get elements from list whose ids are in another

Time:01-27

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?

CodePudding user response:

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

CodePudding user response:

try this

var myNewList = items.Where(p => myIds.Contains( p.id.ToString)).ToList();

CodePudding user response:

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()); 
  •  Tags:  
  • Related