简体   繁体   中英

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 ?

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().ie:

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

wonderful little extension.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM