linq --> changing a value?

B

Berryl Hesh

I start with a list:, {"one", null, "three"}. I want to change the null
value to say "<nothing>" and pass along the entire result (now {"one",
"<nothing>", "three"}.

I can select the null value doing something like the line below, but is
there a way to change it from linq as one might in sql?

Thanks ! BH

new[] {"one", null, "three"}.Where(x=>x == null)
 
M

Martin Honnen

Berryl said:
I start with a list:, {"one", null, "three"}. I want to change the null
value to say "<nothing>" and pass along the entire result (now {"one",
"<nothing>", "three"}.

I can select the null value doing something like the line below, but is
there a way to change it from linq as one might in sql?

With LINQ you processs an IEnumerable<T1> and can get an IEnumerable<T2>
using the Select operator:

List<string> list = new List<string>() { "one", null,
"three" };
IEnumerable<string> query =
list.Select(item => item ?? "<nothing>");
foreach (string item in query)
{
Console.WriteLine(item);
}

Of course, instead of iterating over the query, you could pass it to a
method expecting an IEnumerable<string>.
Or if you want a List<string> as the result you could use

IEnumerable<string> query =
list.Select(item => item ?? "<nothing>").ToList();

if you want an array

IEnumerable<string> query =
list.Select(item => item ?? "<nothing>").ToArray();


So you don't change the existing source of your query, your query
instead constructs a new result.
 
P

Peter Morris

You can create a new list...

var a = new byte[] { 1, 2, 3 };
var b =
(
from val in a
select val == 1 ? 999 : val).ToArray();

otherwise you'll have to use a for() loop and check each element + replace
it.
 
M

Michael C

Berryl Hesh said:
I start with a list:, {"one", null, "three"}. I want to change the null
value to say "<nothing>" and pass along the entire result (now {"one",
"<nothing>", "three"}.

I can select the null value doing something like the line below, but is
there a way to change it from linq as one might in sql?

Thanks ! BH

new[] {"one", null, "three"}.Where(x=>x == null)

Try this:
 
B

Berryl Hesh

It's Good to be Geeky when you can do that even a little bit - thank you!!

-----

if(listSubProjectNumbers == null) {

var temp = (from project in _openProjectsCache orderby
project.SubProjectNumber select project.SubProjectNumber)
.Distinct()
.Select(x => (x ?? "<not valued>")) <<------------- what I got from
this post
.OrderBy(x => x);
_listSubProjectNumbers = new List<string> {_DEFAULT_SELECT_A_VALUE}; //
(Select a value)
_listSubProjectNumbers.AddRange(temp);
}

return listSubProjectNumbers ;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top