Linq SelectMany项目要索引

时间:2013-06-16 18:35:50

标签: c# linq

我有2个不同的收藏品。

伪代码:

// index string by int : Dictionary<int, string>
index = { 0, "a" }, { 1, "b" }, { 2, "c" }

// data : Dictionary<string, List<Data>>
data = {"a", { "data00", "data01"..}}, 
       {"b", {"data20", "data21", "data22"...}}, 
       {"c", {"data4",...}}...

我希望项目int索引到数据字符串值和

var result = data.SelectMany ... new { IntIndex, DataValue }

我需要将列表展平为一个序列,并使用Data索引将int值与string索引配对。

3 个答案:

答案 0 :(得分:1)

我稍微更新了类型和值(您的词典包含重复的键并且未指定索引)但它应该不是问题。您可以轻松修改数据类型的功能。

var index = new List<Tuple<int, string>> {Tuple.Create(0, "a"), Tuple.Create(1, "b")};

var data = new Dictionary<string, IEnumerable<string>>()
    {
        {"a", new[] {"data00", "data01"}},
        {"b", new[] {"data20", "data21", "data22"}},
        {"c", new[] {"data4"}}
    };

var result = index
    .Join(data, x => x.Item2, y => y.Key, (x,y) => new KeyValuePair<int, IEnumerable<string>>(x.Item1, y.Value))
    .SelectMany(x => x.Value, (x, y) => new KeyValuePair<int, string>(x.Key, y));

答案 1 :(得分:1)

假设您keys的重复是偶然的,您可以试试这个

Dictionary<int, List<Data>> intData = new Dictionary<int, List<Data>>();

foreach (var iVal in index)
{
     List<Data> tmpList = new List<Data>();

     if (data.TryGetValue(iVal.Value, out tmpList))
     {
         intData.Add(iVal.Key, tmpList);
     }
}

如果你有重复的密钥,那么字典就不是正确的结构。

答案 2 :(得分:0)

var index = new List<Tuple<int, string>> {Tuple.Create(0, "a"), Tuple.Create(1, "b")};

var data = new Dictionary<string, IEnumerable<string>>()
{
    {"a", new[] {"data00", "data01"}},
    {"b", new[] {"data20", "data21", "data22"}},
    {"c", new[] {"data4"}}
};

var res = 
(from i in index
join d in data on i.Item2 equals d.Key
select new {Key = i.Item1, Value = d.Value})
.SelectMany(x => x.Value, (x, v) => new {x.Key, Value = v});