Linq return null on 'false' where clausule
本文关键字:where clausule false return Linq null on | 更新日期: 2023-09-27 17:59:08
我有一个类似的查询:
var solution = (from hit2 in Hits.Where(x => x.Combination.Count == 2)
where IsPossibleHit(hit2, 2, currentSymbols)
from hit3 in Hits.Where(x => x.Combination.Count == 3)
where IsPossibleHit(hit3, 3, currentSymbols)
from hit4 in Hits.Where(x => x.Combination.Count == 4)
where IsPossibleHit(hit4, 4, currentSymbols)
from hit5 in Hits.Where(x => x.Combination.Count == 5)
where IsPossibleHit(hit5, 5, currentSymbols)
select new
{
hitsList = new List<Hit>(){
hit2,
hit3,
hit4,
hit5}
}).ToList();
我的问题是,在创建组时,如果hit2和hit3是可能的命中,我需要创建新对象,但是,因为hit4返回false,所以整个组合被丢弃。
如何做到这一点?
编辑:我想我没有弄清楚我需要什么,或者我的问题是什么:
我的问题是,当IsPossibleHit(hitN)返回false时,整个组合将被丢弃(由linq),但我需要的是无论如何都要创建对象,返回false的命中设置为null,甚至不添加到新对象的命中列表中。
var solution = (from hit2 in Hits.Where(x => x.Combination.Count == 2)
where IsPossibleHit(hit2, 2, currentSymbols)
let h3 = from hit3 in Hits.Where(x => x.Combination.Count == 3)
where IsPossibleHit(hit3, 3, currentSymbols)
let h4 = from hit4 in Hits.Where(x => x.Combination.Count == 4)
where IsPossibleHit(hit4, 4, currentSymbols)
let h5 = from hit5 in Hits.Where(x => x.Combination.Count == 5)
where IsPossibleHit(hit5, 5, currentSymbols)
select new
{
hitsList = new List<Hit>(){
hit2,
h3,
h4,
h5}
}).ToList();
试试这样的东西。请检查语法,因为我还没有运行或编译它。
我想你想做的是:
var res = Hits.Where(h => h.Combination.Count >= 2
&& h.Combination.Count <= 5
&& IsPossibleHit(h, h.Combination.Count, currentSymbols)
).ToList();
您想按点击数分组,并只保留每组中可能的点击数吗?先用Where
过滤,然后用GroupBy
:过滤
var groupedHits = from h in Hits
where h.Combination.Count >= 2 && h.Combination.Count <= 5
where IsPossibleHit(h, h.Combination.Count, currentSymbols)
group h by h.Combination.Count