简体   繁体   中英

More efficient way to check DataTable values?

I want to iterate through my table, check to see if the Quantity received is higher than the quantity expected for each row, and if so execute some code.

The way I've done it below feels amateurish.

bool allRecieved = true;
foreach (DataRow row in SubVwr.Tables[0].Tbl.Rows)
{
    if(row["QtyRcvd"] < row["QtyPer"]) allRecieved = false;
}
if(allRecieved) // execute code

You can use LINQ, for better readability (presuming those are int -columns):

bool allRecieved = SubVwr.Tables[0].Tbl.AsEnumerable()
    .All(row => row.Field<int>("QtyRcvd") >= row.Field<int>("QtyPer"));

An advantage over your current loop is that this will stop as soon as one record doesn't match this condition. Your loop will continue until end without break .

This is a bit radical, but I'd start by not using DataTable , and instead use a simple model:

public class SomeType {
    // I'd probably name these QuantityReceived etc, but... meh
    public int QtyRcvd {get;set;}
    public int QtyPer {get;set;}
    // ... etc
}

Then I can very conveniently check properties etc. For example, to mirror Tim Schmelter's LINQ answer :

List<SomeType> someData = ...
var allReceived = someData.All(x => x.QtyRcvd >= x.QtyPer);

so now all we need is to load SomeType from the DB, which is where ORMs and micro-ORMs excel. For example, with "Dapper", this would be:

string region = "North"; // just to show parameter usage
var someData = connection.Query<SomeType>(
    @"select * from SomeTable where Region=@region", new { region }).AsList();

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