LINQ 列表<KeyValuePair>

LINQ to List<KeyValuePair>

我目前正在开发 .NET Framework 4.7.2 应用程序。我正在处理 LINQ 查询 selecting 来自给定数据结构的对象:

List<KeyValuePair<int, Dictionary<string, object>>>

这是一个动态对象列表。我需要 select 列表中的所有元素,其中字典中的 valuetrue,关键是 IsDummy案例.

下图显示调试模式下的数据结构xyz

var result = xyz
    .Select(a => a.Value)
    .SelectMany(b => b)
    .Where(c => c.Key == "IsDummy" && (bool)c.Value == true);

我想select一个List<KeyValuePair<int, Dictionary<string, object>>>,其中字典中的值对象是布尔类型,值为真。

很遗憾,我当前的查询无法正常工作。

你知道如何解决这个 LINQ 查询吗?由于列表中的 KeyValuePair 和 Dictionary,这有点棘手。

非常感谢!

这应该有效:

var result = xyz
    .Where(kv => kv.Value.TryGetValue("IsDummy", out object value) 
                 && value is bool b && b); // pattern matching C#7

非 C#7 版本:

...
&& value is bool && (bool)value);

您指定:

I would like to select a List<KeyValuePair<int, Dictionary<string, object>>> where the value object in the dictionary is of type boolean and has the value true.

值对象?这是否意味着列表中的所有词典都只有一个值?

  • 或者您只想要列表中那些具有只有一个值的字典的元素:布尔值是真的?
  • 或者您只希望列表中的那些元素具有至少一个布尔值 true 的字典?
  • 或者所有值都应该是具有真值的布尔值?

.

List<KeyValuePair<int, Dictionary<string, object>>> source = ...
var result = source
    // keep only those items in the list that have a Dictionary with only one value,
    // namely a Boolean that is true
    .Where(pair => pair.Value.Count == 1 
                // pair.Value is a Dictionary; 
                // pair.Value.Values are the values in the Dictionary
                // only keep this item if the one and only value in the dictionary is a Boolean with a value true
                && pair.Value.Values.First().GetType() == typeof(bool)
                && (bool)pair.Value.ValuesFirst());

这可以优化,使用它你将枚举字典两次。我这样保留它是为了提高可读性。

第二个规范:仅保留列表中的元素,这些元素的字典中至少有一个布尔值为真

var result = source
    .Where(pair => pair.Value.Values
         // keep only the values in the dictionary that are Boolean:
         .OfType<bool>()
         // keep only the true values
         .Where(dictionaryValue => dictionaryValue)
         // keep this list item if there is at least one such value in the dictionary
         .Any());

通过这些示例,可以轻松编写字典中所有项目都必须是具有真值的布尔值的版本