c# - 如何使用 LINQ 展平类中的嵌套字典

标签 c# linq

最接近我所寻找的解决方案是这个线程 How to flatten nested objects with linq expression

但是我在尝试这种方法时遇到错误

The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

我的代码:

var aa = t.data.SelectMany(x => 
                    x.Value.innerData.SelectMany(y => new { /*Error at this SelectMany*/
                    url = x.Key,
                    disp = x.Value.disp,
                    date = y.Key,
                    count = y.Value.count,
                    rank = y.Value.rank,
       }));

我的类(class):

public class TData {
    public Dictionary<string, TDetail> data { get; set; }
}

public class TDetail {
    public string disp { get; set; }

    [Newtonsoft.Json.JsonProperty("data")]
    public Dictionary<string, Metrics> innerData { get; set; }

}

public class Metrics {
    public string count { get; set; }
    public string rank { get; set; }
}

我从第 3 方 API 获得的 JSON 如下所示:

{
  "data": {
    "abc.com": {
      "disp": "#712176",
      "data": {
        "2015-02-08": {
          "count": 4,
          "rank": 5.8
        },
        "2015-02-23": {
          "count": 3,
          "rank": 8.3
        },
        "2015-03-14": {
          "count": 5,
          "rank": 3.7
        }
      }
    },
    "nbc.com": {
      "disp": "#822176",
      "data": {
        "2015-02-08": {
          "count": 3,
          "rank": 5.5
        },
        "2015-02-23": {
          "count": 5,
          "rank": 8.4
        },
        "2015-03-14": {
          "count": 7,
          "rank": 4.7
        }
      }
    }
  }
}

在这种情况下如何明确指定类型参数?谢谢。

最佳答案

SelectMany 太多:

var t = new TData(); // your TData

var aa = t.data.SelectMany(x =>
        x.Value.innerData.Select(y => new
        {
            url = x.Key,
            disp = x.Value.disp,
            date = y.Key,
            count = y.Value.count,
            rank = y.Value.rank,
        }));

内部的必须是Select

关于c# - 如何使用 LINQ 展平类中的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30942803/

相关文章:

c# - 使用 C# 检查用户是否已存在于 MySql 数据库中

c# - 如何通过 LINQ 展平树?

c# LinqtoTwitter 从连接上下文获取 ScreenName/UserID

c# - asp.net c# 成员资格 : how to do a GetUsersInRoles (multiple roles)H

c# - LINQ - 按名称分组到 Dictionary<string, List<T>>

c# - 清理 SQL 数据

继承抽象类并实现接口(interface)的 C# 窗体。

c# - 如何重置我的 C# 程序(Windows 移动版)?

c# - 是否有类似 List<T> 的动态数组允许访问 .NET 中的内部数组数据?

c# - LINQ to Entities 不支持“日期”。仅支持初始化器、实体成员和实体导航属性