David
David

Reputation: 45

Linq, exclude SQL Nulls

I'm generating a pie chart, currently I have have the following variable, How to exclude Null records? it works but it includes null values in the pie chart

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();

Upvotes: 1

Views: 80

Answers (3)

Luis Lavieri
Luis Lavieri

Reputation: 4129

You can also write it using lambda expressions:

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

Upvotes: 0

NinjaDeveloper
NinjaDeveloper

Reputation: 1712

if T1 is Nullable use HasValue Property

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() };

Upvotes: 2

hnefatl
hnefatl

Reputation: 6037

Add a where clause to filter the null values before you use them - here I'm assuming that either T1 or T1.Reasons can be 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() };

I also suspect that orderby count ascending should be orderby G1.Count() ascending.

Upvotes: 1

Related Questions