2012-04-13 53 views
0

我想使用linq过滤数据表中的数据。C#Linq过滤器使用数组元素的数据表

我的情况是我有一个包含日期动态创建,并在数据表中我们列作为id,date,etc.

我们要检索的ID包含在阵列

前所有日期元素的数组:

string[] arr={"10/10/2012","11/11/2012","9/9/2012"} 

表:

ID date  
1 10/10/2012   
2 11/11/2012   
1 9/9/2012   
6 9/9/2012   
3 9/9/2012   
6 11/11/2012   
1 11/11/2012   

输出将为1 - 因为只有id'1'具有所有数组元素。

要完成上述功能,我使用下面显示的Linq查询。但我从字面上来说是失败的。

Dim volunteers As DataTable = 
    (From leftTable In dtavailableVolunteers.AsEnumerable() 
    Join rightTable In dtavailableVolunteers.AsEnumerable() 
     On leftTable.VolunteerId Equals rightTable.VolunteerId 
    Where SelectedDatesArray.All(Function(i) rightTable.Field(Of String)("SelectedDate").Equals(i.ToString())) 
    Select rightTable).CopyToDataTable() 

回答

0

比方说你的数据表是DT

DataRow[] dr = dt.Select("date in (" + string.join("," , arr) + ")"); 

string[] st = dr.Select(ss => ss["id"].ToString()).ToArray(); 

OR

DataTable newdt = dr.CopyToDataTable(); 

下联是LINQ

+0

这将使你匹配任何日期的标识。 OP的要求是匹配所有的日期。 – 2012-04-13 14:19:12

0

你可以按ID行,然后找到该组其中:不存在组的日期不包含该元素的arr元素。我的意思是这样的:

var result = from item in list 
      group item by item.ID into grouping 
      where !arr.Exists(date => 
       !grouping.Select(x => x.Date).Contains(date)) 
      select grouping.Key; 
0

这里是另一个版本:

from volunteer in dtavailableVolunteers 
group volunteer by volunteer.Id into g 
let volunteerDates = g.Select(groupedElement=>groupedElement.date) 
where arr.All(date=>volunteerDates.Contains(date)) 
select g.Key