如果值在先前的记录中,则在linq查询中选择null [英] Select null in a linq query if the value is in a previous record
本文介绍了如果值在先前的记录中,则在linq查询中选择null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下查询:
var ds = (from t1 in list1
from t2 in list2
select new {t1.Name, t2.Name}
).ToList();
这将返回类似的内容:(粗略表示)
This returns something like: (rough representation)
Name1, InnerName1
Name1, InnerName2
Name2, InnerName1
Name2, InnerName2
我想得到的是:
Name1, InnerName1
Null, InnerName2
Name2, InnerName1
Null, InnerName2.
意思是,如果我已经在列表中包含t1.Name,我想在t1的其余结果中使用null或空字符串.
我已经知道我可以遍历结果,但是我将其用作数据源,并且希望基于集合进行操作.
I already know that I could loop through the results, but I'm using this as a datasource and would like to do something set based.
有没有办法在单个查询中完成此操作?
Is there a way to accomplish this in a single query?
推荐答案
假设您使用Linq-to-Objects,则可以执行以下操作:
Assuming your using Linq-to-Objects, you could do something like this:
string previous = null;
var results =
(from t1 in list1
from t2 in list2
select new {
Name1 = (previous == t1.Name) ? null : (previous = t1.Name),
Name2 = t2.Name
})
.ToList();
但是这依赖于副作用,而且不是特别优雅.您可能会喜欢这样的东西:
But that relies on side effects and isn't particularly elegant. You might prefer something like this:
var result =
(from t1 in list1
select
list2.Take(1)
.Select(t2 => new { Name1 = t1.Name, Name2 = t2.Name })
.Concat(list2.Skip(1)
.Select(t2 => new { Name1 = (string)null, Name2 = t2.Name }))
.SelectMany(x => x)
.ToList();
这篇关于如果值在先前的记录中,则在linq查询中选择null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文