Jazimov Jazimov - 1 month ago 7
C# Question

Add List Element Based on Conditional with Linq Expression

I have this very simple Linq query (the .Dump() function is being used with LinqPad in order to view the results):

void Main()
{
var myList = new List<string>
{
"One", "Two", "Three"
};


var result = from o in myList
select o;

result.Dump();
}


How can I inject an if statement into the Linq query that populates
result
so that it checks to see if "Four" is in the list--and if it is not, then add it? I realize that there are ways to do this by looking at result after Linq has populated
result
, but I would like to add this logic into a single Linq query.

Thank you.

EDIT/CLARIFICATION: The "if" logic needs to be inside the Linq query. Here is the skeletal code:

var result = from o in myList
select o
[now add "four" if and only if it is not in the result]
[now end the query and ensure `result` contains "one", "two", "three", and "four"];


SECOND EDIT:
I am trying to query and add to the list in a single operation. By the way, I made this very simple example instead of giving the much more complex scenario I'm trying to handle, by the way, so it's not as if I am struggling with how to add a new element to a List object. :)

So here is what I was going to do:

// query the list to see if "four" is in the list
(a Linq query goes here to check for "four")

// if the result of the above is false then add "four" to the myArray List
(add the new array element here)

Instead, I would like to do the following:

// query the list for its contents and also add "four" if it is not in the list.
// all this needs to be done in a single "select" using Linq

Is this not possible?

Thank you.

Answer

You can use Union if you switch to method syntax:

var result = myList.Union(new [] {"Four"});

There's not really a clean way to to it using just query syntax. Query syntax only supports a small set of Linq operators, of which union is not one.