c# - IEnumerable<string> 到字典<char, IEnumerable<string>>

标签 c# linq dictionary ienumerable

我认为这个问题可能部分重复其他类似的问题,但我在这种情况下遇到了麻烦:

我想从一些字符串句子中提取

例如来自

`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);

上面给出的解决方案使一切正常,但它提供了我不需要的其他类型。

enter image description here 我应该做什么才能得到结果 Dictionary<char, IEnumerable<string>>dictionary 但不是 Dictionary<IGouping<'a,'a>>

我想要的结果如下图所示: enter image description here 但在这里我必须迭代 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/

相关文章:

c# - "EntityType has no key defined"异常,尽管键是用 HasKey 定义的

c# - Linq 查询数据源,InvalidOperationException

c# - 需要一种高效的方法来从列表中返回所有重复项

ios - 如何在 Swift 中使用 (?) 和 (!)

javascript - 如何根据选中的复选框计算总数?

c# - 如何使用 JSON.net 格式化嵌套 JSON 对象的输出?

c# - 如何使用WinForms进度条?

c# - 使用 linq.. 将通用列表转换为数据表?

java - Map<> 中的entrySet() 上的add() 方法

c# - 字典获取具有最高值和键的项目