我认为这个问题可能部分重复其他类似的问题,但我在这种情况下遇到了麻烦:
我想从一些字符串句子中提取
例如来自
`string sentence = "We can store these chars in separate variables. We can also test against other string characters.";`
我想构建一个 IEnumerable 单词;
var separators = new[] {',', ' ', '.'};
IEnumerable<string> words = sentence.Split(separators, StringSplitOptions.RemoveEmptyEntries);
之后,完成所有这些words
并将第一个字符放入一个独特的升序字符集合中。
var firstChars = words.Select(x => x.ToCharArray().First()).OrderBy(x => x).Distinct();
之后,遍历两个集合以及 firstChars
中的每个字符。获取全部items
来自words
其中有 first character
等于 current character
并创建一个 Dictionary<char, IEnumerable<string>> dictionary
.
我这样做:
var dictionary = (from k in firstChars
from v in words
where v.ToCharArray().First().Equals(k)
select new { k, v })
.ToDictionary(x => x);
问题是:An item with the same key has already been added.
这是因为在该字典中它将添加一个现有的字符。
我添加了 GroupBy
扩展到我的查询
var dictionary = (from k in firstChars
from v in words
where v.ToCharArray().First().Equals(k)
select new { k, v })
.GroupBy(x => x)
.ToDictionary(x => x);
上面给出的解决方案使一切正常,但它提供了我不需要的其他类型。
我应该做什么才能得到结果 Dictionary<char, IEnumerable<string>>dictionary
但不是 Dictionary<IGouping<'a,'a>>
?
我想要的结果如下图所示: 但在这里我必须迭代 2 个 foreach(s),这将告诉我我想要什么...我不太明白这是如何发生的...
欢迎任何建议和意见。谢谢。
最佳答案
由于关系是一对多,因此您可以使用查找而不是字典:
var lookup = words.ToLookup(word => word[0]);
loopkup['s'] -> store, separate... as an IEnumerable<string>
如果您想显示按第一个字符排序的键/值:
for (var sortedEntry in lookup.OrderBy(entry => entry.Key))
{
Console.WriteLine(string.Format("First letter: {0}", sortedEntry.Key);
foreach (string word in sortedEntry)
{
Console.WriteLine(word);
}
}
关于c# - IEnumerable<string> 到字典<char, IEnumerable<string>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17236959/