Reputation: 542
Suppose I have 2 DataTables, DSALL and DSSome for storing student information
DSALL (Store all student information)
SID (PK)
Name
Address
Telephone
...
DSSome (Store only SID for some specific students)
SID (Unique)
Now I want a C# function to check if all SID in DSSome exist in DSALL. The function return true if all SID exist in DSALL, return false if otherwise.
The traditional way is
protected bool checkSID(DataTable DSALL, DataTable DSSome){
for (int i=0; i<DSSome.Rows.Count; i++){
bool isFound = false;
string SID = DSSome.Rows[i]["SID"].ToString();
for (int j=0; j<DSALL.Rows.Count; j++){
string _SID = DSALL.Rows[j]["SID"].ToString();
if (SID == _SID) { isFound = true; break; }
}
if (!isFound) return false;
}
return true;
}
Is there any other simpler way of efficient way to solve this problem?
Upvotes: 0
Views: 1762
Reputation: 66499
Here's another option. It grabs all SIDs from DSSOME, except those that occur in DSALL. If there are any values left-over in DSSOME that don't exist in DSALL, .Any()
will return true
.
Then you can just negate the value, since you wanted to return true
if there weren't any left-over values in DSSOME.
return !DSSome.Rows.Cast<DataRow>().Select(x => x["SID"])
.Except(DSALL.Rows.Cast<DataRow>().Select(x => x["SID"])).Any();
Upvotes: 1
Reputation: 39278
return DSSome.Rows.OfType<DataRow>()
.All(r => DSAll.Rows.OfType<DataRow>()
.Where(x => (string)x["SID"] == (string)r["SID"]).Count() == 1)
This is using a linq query to compare values from the two sets. The OfType<> is used to convert the Rows collection to Rows<DataRow>
in order to use LINQ. All() will return true if all rows met the criteria. It returns false otherwise.
Upvotes: 1