如何在IGrouping <string,topic> </string,topic>中将剩余的字母添加到此查询中

时间:2011-05-11 18:17:46

标签: c# linq

我想根据单词的第一个字母对这些项目进行分组,以下查询工作正常。但我想修改它并包括该分组的所有字母,无论该项目是否存在。我该如何解决这个问题?

查询是: -

  var qry = from row in item.Topics
                              group row by row.Title[0].ToString().ToLower() into groupedItems
                              orderby groupedItems.Key
                              select new Group<Topic>(groupedItems.Key, groupedItems);

1 个答案:

答案 0 :(得分:1)

听起来你想在a,b,c,... z范围内进行外连接?

有几种方法可以做到这一点。例如,您可以尝试:

        var qry = from row in "LifeLikeThis"
                  group row by row.ToString().ToLower()
                  into groupedItems
                  orderby groupedItems.Key
                  select new {Key = groupedItems.Key, Items = groupedItems};

        var alphaQry = from character in "abcdefghijklmnopqrstuvwxyz"
                       join grp in qry on character.ToString() equals grp.Key into joined
                       from joinGroup in joined.DefaultIfEmpty()
                       select new {Key = character.ToString(), Items = joinGroup == null ? null : joinGroup.Items};

这是joined.DefaultIfEmpty()的关键部分。有关外连接的详细信息,请参阅101个样本 - http://msdn.microsoft.com/en-us/vcsharp/ee908647#leftouterjoin