我想创建一个通用LINQ
函数来对我数据库中select
的结果进行分组。但是,对于每个数据库表,我应该有group by
个不同的表。基本上,我要做的是
将table1
的结果分组为columnName1
和columnName2
:
from element in databaseRows
group element by
new { column1 => element.Value("columnName1"), column2 => element.Value("columnName2")}
into g
select new { key = g.Key, value = g };
将table2
的结果分组为columnName3
:
from element in databaseRows
group element by
new { column1 => element.Value("columnName3")}
into g
select new { key = g.Key, value = g };
我想创建一个通用函数来接收它必须分组的列列表,如下所示:
from element in databaseRows
group element by
new {
foreach (var v in columnsList)
element.Value(v);
}
into g
select new { key = g.Key, value = g };
我知道我不能这样做,但还有其他办法吗?
答案 0 :(得分:0)
从您拥有的项目到对象数组创建投影非常简单,其中该数组表示给定列名称集合的值:
public class SequenceComparer<T> : IEqualityComparer<IEnumerable<T>>
{
private IEqualityComparer<T> comparer;
public SequenceComparer(IEqualityComparer<T> comparer = null)
{
comparer = comparer ?? EqualityComparer<T>.Default;
}
public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
{
return x.SequenceEqual(y, comparer);
}
public int GetHashCode(IEnumerable<T> sequence)
{
unchecked
{
int hash = 19;
foreach (var item in sequence)
hash = hash * 79 + comparer.GetHashCode(item);
return hash;
}
}
}
问题是如何对字符串值数组进行分组,因为默认的相等比较器将比较引用而不是值。下面的比较器将能够根据序列中的值比较值的序列,而不是序列的标识:
var query = databaseRows.GroupBy(GetProperties(columnsList),
new SequenceComparer<string>());
现在我们可以写:
{{1}}