使用linq加入特定的2行现有列表

时间:2017-01-24 15:30:13

标签: c# linq

我有一个问题,我有一个列表让我们说:

List<string> list = new List<string> { A, B, C, D, E, F, G}

我需要将该列表的特定两行组合到新的新列表中,例如:

List<string> rebuildList = new List<string> { A, B, CD, E, FG}

我已经制作了一个可行的代码:

var joinDictionary = new Dictionary<int, int> { { 3, 4 }, { 7, 8 } };
foreach (var value in list)
{
    var index = list.IndexOf(value);
    if (joinDictionary.ContainsKey(index))
    {
        rebuildList.Add(string.Format("{0} {1}", value, list.ElementAt(index + 1)));
    }

    if (!joinDictionary.ContainsKey(index) && !joinDictionary.ContainsValue(index))
    {
        rebuildList.Add(value);
    }
}

但是有更优雅的方法吗? Sole linq lambda查询可能吗?

1 个答案:

答案 0 :(得分:1)

如果您将字典更改为零,则可以使用以下内容:

list.
    Select((str, ind) => joinDictionary.ContainsKey(ind) ? str + list[joinDictionary[ind]] : str).
    Where((str, ind) => !joinDictionary.ContainsValue(ind)).
    ToList();

这是一个单行,但我不确定它是否比您的解决方案更具可读性。

如果您不想切换到基于零的字典,则必须使用LINQ表达式中的索引。