Linq,排除SQL Nulls

时间:2018-04-25 19:42:47

标签: c# linq

我正在生成饼图,目前我有以下变量,如何排除空记录?它可以工作,但它在饼图中包含空值

var PieChartData1 = from T1 in Result
                    group T1 by T1.Reasons  into G1
                    orderby count ascending
                    select new { G1.Key, Count = G1.Count()  };
 obj.peichart1 = PieChartData1.ToArray();

3 个答案:

答案 0 :(得分:1)

添加where子句以在使用null值之前对其进行过滤 - 此处我假设T1T1.Reasons可以是{{1} }}:

null

我还怀疑var PieChartData1 = from T1 in Result where T1 != null && T1.Reasons != null group T1 by T1.Reasons into G1 orderby count ascending select new { G1.Key, Count = G1.Count() }; 应为orderby count ascending

答案 1 :(得分:1)

如果T1为Nullable,请使用HasValue属性

var PieChartData1 = from T1 in Result
                        where T1.HasValue
                        group T1 by T1.Reasons into G1
                        orderby count ascending
                        select new { G1.Key, Count = G1.Count() };

答案 2 :(得分:0)

您也可以使用lambda表达式编写它:

var pieChartData = Result.Where(r => r.Reason != null)
                         .GroupBy(r => r.Reason)
                         .OrderBy(g => g.Count())
                         .Select(g => new { g.Key, Count = g.Count() });