Reputation: 1
I have a DataTable
named dt
. It has two Columns named atype_code
and module
.
Now i need to query a module based on specific atype_code
.
Here is the code i wrote but not working.
DataTable dt = GetATypeCodeList();
var accType = (from myAccType in dt.AsEnumerable()
where myAccType.Field<string>("atype_code") == aTypeCode.Trim()
select myAccType.Field<string>("module"));
acctype
is a System.Data.EnumerableRowCollection<System.String>
.
Upvotes: 0
Views: 1206
Reputation: 460018
Since you've said that you
need to query a module based on specific atype_code
, i assume that you want only one module
with the given atype_code
.
Then you should either use Single
/SingleOrDefault
or First
/FirstOrDefault
.
String firstModule = dt.AsEnumerable()
.Where(r => r.Field<string>("atype_code") == aTypeCode.Trim())
.Select(r => r.Field<string>("module"))
.FirstOrDefault();
// or
String singleModule = dt.AsEnumerable()
.Where(r => r.Field<string>("atype_code") == aTypeCode.Trim())
.Select(r => r.Field<string>("module"))
.SingleOrDefault();
Enumerable.Single
throws an exception if there is more than one matching element. That can be useful to validate the data.
Edit:
Here's the query-syntax:
IEnumerable<String> modules =
from myAccType in dt.AsEnumerable()
where myAccType.Field<string>("atype_code") == aTypeCode.Trim()
select myAccType.Field<string>("module");
String module = modules.FirstOrDefault(); // returns null if no matching modules were found
Upvotes: 1