Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this achievable with a single LINQ query?

Suppose I have a given object of type IEnumerable<string> which is the return value of method SomeMethod(), and which contains no repeated elements. I would like to be able to "zip" the following lines in a single LINQ query:

IEnumerable<string> someList = SomeMethod();

if (someList.Contains(givenString))
{
    return (someList.Where(givenString));
}
else
{
    return (someList);
}

Edit: I mistakenly used Single instead of First. Corrected now.

I know I can "zip" this by using the ternary operator, but that's just not the point. I would just list to be able to achieve this with a single line. Is that possible?

like image 476
DotNetStudent Avatar asked Feb 22 '23 17:02

DotNetStudent


1 Answers

This will return items with given string or all items if given is not present in the list:

someList.Where(i => i == givenString || !someList.Contains(givenString))
like image 70
Joe Avatar answered Mar 08 '23 23:03

Joe