需要Linq的帮助。
我有一个数据表,如下所示 I just have the W_text with me to search
使用上面的数据表,我想提取具有以下结果的行子集
The key to search is "First Employee"
正如您所看到的,我想获得那些具有W_Text值的行的子集" First"和"员工"但具有相同的l_id。
在数据库术语中,这将是表1中的Select *,其中W_Text在(' First',#39; Employee')组中由l_id具有l_id> 1(或类似的东西)。
如何使用数据表在C#中实现此目的?
我尝试使用以下代码,但这也为我提供了包含其他行的整个数据表。我不知道如何使用group by和having子句。如果有人可以在这方面帮助我,我会指出。
var results = from myRow in dtResult.AsEnumerable()
where myRow.Field<string>("W_Text") == "First" ||
myRow.Field<string>("W_Text") == "Employee"
select myRow;
dtCopy = results.CopyToDataTable();
答案 0 :(得分:0)
嗨,你可以像这样使用
var results = (from myRow in dtResult.AsEnumerable()
where myRow.Field<string>("W_Text") == "First" ||
myRow.Field<string>("W_Text") == "Employee"
select myRow ).ToLookup(item => item.Field<string>("l_id"));
OR
var results = (from myRow in dtResult.AsEnumerable()
where myRow.Field<string>("W_Text") == "First" ||
myRow.Field<string>("W_Text") == "Employee"
select myRow).GroupBy(item => item.Field<string>("l_id")).ToList();
答案 1 :(得分:0)
检查以下内容:
List<string> wTextFilter = new List<string>();
wTextFilter.Add("First");
wTextFilter.Add("Employee");
// Get all Id's that satisfy all conditions:
List<int> results = dt.AsEnumerable()
// Get all Id's:
.Select(dataRow => dataRow.Field<int>("l_id"))
// Filter the Id's :
.Where(id =>
// the Id should be greater than one.
id > 1 &&
// check if all W_Text entries has a record in the datatable with the same Id.
wTextFilter.All(W_Text => dt.AsEnumerable().Any(dataRow => dataRow.Field<string>("W_Text") == W_Text && dataRow.Field<int>("l_id") == id)))
.Distinct().ToList();
// Get all datatable rows filtered by the list of Id's.
DataTable dtCopy = dt.AsEnumerable().Where(dataRow => results.Contains((dataRow.Field<int>("l_id")))).CopyToDataTable();