[英]Group by a list of words by their first letter in LINQ
I have to group by first letter of the word in LINQ. 我必须按LINQ中单词的第一个字母分组。 Since i'm new to LINQ i'm not aware of debugging into it.
由于我是LINQ的新手,所以我不知道对其进行调试。
//Code //码
var words4 = testDS.Tables["Words4"].AsEnumerable();
var wordGroups =
from w in words4
group w by w.Field<string>("word")[0] into g
select new {FirstLetter = g.Key, Words = g };
foreach (var g in wordGroups)
{
Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
Console.WriteLine(g.Field<string>("word"));
}
Its throwing "Invalid Arguments" execption in the last Console.WriteLine. 在最后一个Console.WriteLine中抛出“无效参数”的执行。
Try Adding a loop inside so you can get the results more accurately. 尝试在内部添加循环,这样您可以更准确地获得结果。
Replace: 更换:
Console.WriteLine(g.Field<string>("word"));
With: 带有:
foreach (var w in g.Words)
{
Console.WriteLine(w.Field<string>("word"));
}
Since in your select
, you created an anonymous object with field specified as Words
and later you are accessing it through word
, Also the Field
extension method is not required. 由于在
select
,您创建了一个匿名对象,其字段指定为Words
,以后您将通过word
访问它,而且不需要Field
扩展方法。
You need to replace: 您需要更换:
Console.WriteLine(g.Field<string>("word"));
with 与
Console.WriteLine(g.Words);
First, rather than your group consisting of DataRows, since you only want to show the words, I would select the words you want out of the datarow. 首先,由于您只想显示单词,而不是由DataRows组成的组,所以我将从数据行中选择想要的单词。 Second, remember that the words are in a list.
其次,请记住单词在列表中。 If you want to print them out, you'll need to loop or do something like string.Join (as I do below).
如果要打印出来,则需要循环或执行类似string.Join的操作(如下所述)。 For example:
例如:
var wordGroups =
from w in words4.Select(w => w.Field<string>("word"))
group w by w[0] into g
select new { FirstLetter = g.Key, Words = g };
foreach (var g in wordGroups) {
Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
Console.WriteLine(string.Join(", ", g.Words));
}
This should fetch what you want from within wordGroups
, using Linq syntax: 这应该使用Linq语法从
wordGroups
获取所需内容:
Replace: 更换:
Console.WriteLine(g.Field<string>("word"));
with: 与:
g.Words.ForEach(w => Console.WriteLine(W.Field<string>("word"));
另一个选择是这样的吗?
Dictionary<string, List<Product>> groupedDictionary = _db.Products.GroupBy(g => g.Name.Substring(0,1)).ToDictionary(g => g.Key, g => g.ToList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.