Cemre Mengü
Cemre Mengü

Reputation: 18754

C# - Check if the RESULT returned by a linq query on a DataTable has rows

I usually query datatables with linq to filter data such as:

var plan = from p in planData.AsEnumerable()
let rnk = p.Field<decimal?>("RANK")
let spd = p.Field<string>("SPEED")
where rnk.HasValue
&& rnk == Convert.ToInt32(rank)
   && spd == speed
select p;

where planData is a datatable. The problem is that I have no simple way of check if the result returns anything. I cannot use any useful methods at all (like ToList , AsEnumerable) on the plan variable. All I can do is try to loop and see if there were anything returned.

Any ideas how I can get around this ? Maybe there is another way to select data from a datatable ?

Upvotes: 0

Views: 4053

Answers (1)

jim tollan
jim tollan

Reputation: 22485

Use the inbuilt test:

if(plan.Any())
{
   //... do stuff
}

you can also use the nice little override on that, to test for the existence of items in Any().i.e:

if(plan.Any(x => x.IsValid))
{
   //... do stuff
}

wonderful little extension.

[update] -include the using System.Linq; using also

Upvotes: 8

Related Questions