2012-02-16 45 views
0

我有字符串的数组说:Linq查询组由多个列

String[] Fields=new String[]{RowField,RowField1} 

在,我可以使用下面的查询通过指定值来获得值的查询,即RowField和RowField1:

var Result = (
from x in _dataTable.AsEnumerable() 
select new 
{ 
    Name = x.Field<object>(RowField), 
    Name1 = x.Field<object>(RowField1) 
}) 
.Distinct(); 

但如果假设我在像阵有很多价值:

String[] Fields= new String[] 
{ 
    RowField, 
    RowField1, 
    RowField2, 
    ....... 
    RowField1000 
}; 

我如何在这里使用的查询withou在查询中指定每个rowfield? 如何迭代LINQ中的数组项?

根据LINQ query and Array of string中的一些建议,我尝试使用下面的代码得到结果。

var result = (from row in _dataTable.AsEnumerable() 
       let projection = from fieldName in fields 
         select new {Name = fieldName, Value = row[fieldName]} 
       select projection.ToDictionary(p=>p.Name,p=>p.Value)) 
      .Distinct(); 

但问题是它不返回不同的values.Any想法?

回答

0

开始具有鲜明的DataRows使用this overload of Distinct()

_dataTable.AsEnumerable().Distinct(new DataRowEqualityComparer()) 

其中DataRowEqualityComparer是:

public class DataRowEqualityComparer : IEqualityComparer<DataRow> 
{ 
    public bool Equals(DataRow x, DataRow y) 
    { 
     return x.ItemArray.SequenceEqual(y.ItemArray); 
    } 

    public int GetHashCode(DataRow obj) 
    { 
     return string.Join("", obj.ItemArray).GetHashCode(); 
    } 
}