Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading