C# Linq 将列表作为值添加到字典中

标签 c# linq

我有这样一本字典:

Dictionary<string, List<myobject>>

当我得到新的元素时,我正在做这样的逻辑:

mydictionary[key].add(mynewobject);

现在,我正尝试对 LINQ 做同样的事情,但我卡在了最后一行: (请忽略代码中一些不相关的逻辑):

var Test =
    (from F in Directory.EnumerateFiles(SOURCE_FOLDER, SOURCE_EXTENSIONS, SearchOption.AllDirectories)
    let Key = ParenthesisGroupRegex.Replace(F.ToLower(), string.Empty).Trim()
    let Descriptions =
        (from Match Match in ParenthesisGroupRegex.Matches(F.ToLower())
        let CleanedMatches = ParenthesisRegex.Replace(Match.Name, string.Empty)
        let MatchesList = CleanedMatches.Split(',')
        select new Description { Filename = F, Tag = MatchesList.ToList() })
    group Descriptions by Key into DescriptionList
    select new KeyValuePair<string, IEnumerable<string>>(Key, DescriptionList))

如果我们看一下最后两行: 我正在尝试获取我的列表(列表

在最后一行,我正在尝试构建字典条目,但这不会编译,因为在那个阶段看起来 Key 和 DescriptionList 都不可访问。

(顺便说一句,我目前正在学习 LINQ 语法,所以可读性和可维护性不是现在的重点)

我错过了什么?

最佳答案

您可以调用 ToDictionary在您定义的查询结束时:

var Test =
(from F in Directory.EnumerateFiles(SOURCE_FOLDER, SOURCE_EXTENSIONS, SearchOption.AllDirectories)
let Key = ParenthesisGroupRegex.Replace(F.ToLower(), string.Empty).Trim()
let Descriptions =
    (from Match Match in ParenthesisGroupRegex.Matches(F.ToLower())
    let CleanedMatches = ParenthesisRegex.Replace(Match.Name, string.Empty)
    let MatchesList = CleanedMatches.Split(',')
    select new Description { Filename = F, Tag = MatchesList.ToList() })
group Descriptions by Key)
.ToDictionary(x=>x.Key,x=>x.ToList());

本质上 GroupBy如其所述here :

Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.

它的签名如下:

public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector
)

注意 GroupBy 的返回类型这是

IEnumerable<IGrouping<TKey, TElement>>

上面的类型本质上声明了一系列键和与这些键相关联的对象集合(更正式地说,它声明了一个类型为 IGrouping<TKey, TElement> 的对象序列,其中 IGrouping 表示具有公共(public)属性的对象集合 key 。)。您想要的是一个字典,其中包含此序列中的键,并为相应的对象集合赋值。如上所述,这可以通过调用 ToDictionary 来实现。方法。

关于C# Linq 将列表作为值添加到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47357342/

相关文章:

c# - 在类型转换中执行 C# 空检查的简便方法

c# - 文本 block 绑定(bind)不会在运行时更新

linq - Entity Framework /LINQ : Selecting columns from multiple tables?

c# - 订购我的 LINQ

c# - 使用 Json.NET 填充不可序列化对象

c# - 关于将 POCO 从一层转换为另一层 POCO 的设计问题

c# - 在 C++ IDL 中定义结构,然后在 C# 中适本地定义 MarshalAs()

c# - 如何在没有返回值的情况下从 Linq 语句调用函数?

c# - 替换多个 JObject 中属性的 JSON 值

c# - 如何使用匿名 LINQ 结果填充 DataTable