具有动态linq的组的顺序

时间:2014-09-29 20:26:51

标签: c# linq

与这个问题有些相似:

Where do I put the "orderby group.key" in this LINQ statement?

除了我使用Dynamic.Linq,这使得这有点困难。我有一堆数据来自数据库,然后我按一些字段分组,然后输出结果。问题是组的排序似乎随机跳转,这对最终用户来说不是很方便。所以从相关问题中获取灵感,如果我有这个:

string[] words = { "boy","car", "apple", "bill", "crow", "brown" };
// note the first non-dynamic select here was just because I don't think dynamic linq 
// will support indexing a string like that and it's not an important detail anyway
var wordList = words.Select(w => new {FirstLetter = w[0], Word = w})
                    .GroupBy("new (FirstLetter)","Word");  

foreach(IGrouping<object, dynamic> g in wordList)
{
    Console.WriteLine("Words that being with {0}:",
        g.Key.ToString().ToUpper());
    foreach (var word in g)
        Console.WriteLine("  " + word);
}

Console.ReadLine();

如何订购钥匙?问题的至少一部分是动态GroupBy返回IEnumerable。我觉得它可能很简单:

var wordList = words.Select(w => new {FirstLetter = w[0], Word = w})
                    .GroupBy("new (FirstLetter)","Word")
                    .OrderBy("Key"); 

但是当它到达System.ArgumentException循环时,它会给我一个At least one object must implement IComparable.foreach)。

我项目中的实际代码有点复杂,看起来像这样:

var colGroup = row.GroupBy(string.Format("new({0})", 
                           string.Join(",", c)), string.Format("new({0})", 
                           string.Join(",", v)));

其中c是我需要分组的字符串列表,v是我需要在每个组中选择的字符串列表。

2 个答案:

答案 0 :(得分:1)

好的 - 这是一种方法,但它可能有点静态有用。问题是我有这个部分:

.GroupBy("new (FirstLetter)","Word");  

使用new,因为我无法使用值类型作为键(我还有另外一个问题:https://stackoverflow.com/a/26022002/1250301)。使用OrderBy("Key")部分时,问题是它没有办法比较这些动态类型。我可以这样解决:

var wordList = words.Select(w => new {FirstLetter = w[0].ToString(), Word = w})
                    .GroupBy("FirstLetter","Word")
                    .OrderBy("Key"); 

将密钥设为字符串。或者像这样:

var wordList = words.Select(w => new {FirstLetter = w[0], Word = w})
                    .GroupBy("new (FirstLetter as k)","Word")
                    .OrderBy("Key.k");

通过可比较的东西(char)进行排序。

我可以让它与我这样的实际问题一起工作(但它有点难看):

var colGroup = row.GroupBy(string.Format("new({0})", string.Join(",", c)),
                           string.Format("new({0})", string.Join(",", v)))
                  .OrderBy(string.Join(",", c.Select(ob => string.Format("Key.{0}", ob))));

答案 1 :(得分:0)

我不确定你要做什么,但是语法甚至编译了吗?

尝试:

string[] words = { "boy","car", "apple", "bill", "crow", "brown" };

var wordList = words.Select(w => new {FirstLetter = w[0], Word = w})
                    .GroupBy(x => x.FirstLetter, x => x.Word)
                    .OrderBy(x => x.Key);