How to change a value without new projection in LINQ?
I have the following LINQ query:
var source = from node in MyNods
select new
{
Id = node.Id,
Name = node.Name,
ParentId = node.ParentId, // Nullable
};
In the query above, the ParentId
is nullable. Now I need a new result which is match the first one but with small change that if ParentId
is null I want it to be 0
.
I wrote this:
var source2 = from s in source
select new
{
Id = s.Id,
Name = s.Name,
Par开发者_如何学运维entId = s.ParentId ?? 0, // Just change null values to 0
};
Can I implement that with a simpler way (I mean without the new projection) ?
Edit: The new projection is the same of the first one and both ParentId
are nullable.
LINQ isn't ideal for executing side-effects on an existing collection. If that's what you want to do, you'd be better off doing:
foreach(var node in MyNods)
{
if(!node.ParentId.HasValue)
node.ParentId = 0;
}
If that's not the case, you're going to have to project. Your existing query is perfectly fine; the only way I can think of shortening it is:
var source2 = from s in source
select new
{
s.Id, s.Name,
ParentId = s.ParentId ?? 0
};
EDIT: It appears you're trying to create an instance of a different type (i.e. with virtually the same properties as the source but with one specific property being non-nullable), so you can't escape creating instances of the new type and copying properties over. You might want to consider writing a 'real' (non-anonymous) type that represents what you want and get the source-type to provide a conversion-method. Then you can do:
var source2 = source.Select(s => s.ToNonNullableParentVersion());
EDIT: From your edit, it now appears that you don't need a different type to represent the projected data since the 'coalesced' property is still meant to be nullable. If you don't want to mutate the existing collection and you don't like your current query, your best bet would still be to write a conversion method in the source-type.
精彩评论