Home > Software engineering >  How to find element in one of two lists
How to find element in one of two lists

Time:01-08

I can search a list, I was using this:

if (!mylist.Any(item => item.Thing == searchitem))
    {
        var myvar = mylist.Find(item => item.Thing == searchitem);
    }

However, there's a scenario where I can't find the item. And in that case I want to search another list. I'd like to do something like the following but get an error (var myvar triggers: implicitly typed variable must be initialized).

var myvar;
if (!mylist.Any(item => item.Thing == searchitem))
{
    myvar = mylist.Find(item => item.Thing == searchitem);
}
else
{
    myvar = mylist.Find(item => item.Thing == searchitem);
}
mystring = myvar.Thing;

I'm open to another structure of list.Find for achieving the same result but I really want to use myvar further in my code and not have two variables.

CodePudding user response:

You cannot use var without initialization, because a compiler does not know what type it is. Just change to explicit type of your list element type.

For example you have List<int> so your variable should be int myvar.

CodePudding user response:

You scan myList twice: first in Any then in Find. You can try FirstOrDefault:

// Either found item or null (assuming that item is class)
var myvar = myList.FirstOrDefault(item => item.Thing == searchitem);

If you have two lists:

var myvar = myList.FirstOrDefault(item => item.Thing == searchitem) ??
            myList2.FirstOrDefault(item => item.Thing == searchitem);

Finally, if you have several lists (let's organize them into a collection myLists):

var myvar = myLists
  .SelectMany(list => list)
  .FirstOrDefault(item => item.Thing == searchitem);
  • Related