【问题标题】:How to get a list of bundle items with last string in next bundle [duplicate]如何在下一个捆绑包中获取包含最后一个字符串的捆绑包项目列表[重复]
【发布时间】:2020-07-01 18:14:55
【问题描述】:
Given a list of strings:
"A"
"B"
"C"
"D"

我希望得到一个包含 2 个项目的列表,每个项目都重复第二个项目:

“A”、“B”

“B”、“C”

“C”、“D”

我正在尝试的是下一个可能更好的解决方案?

        //result = List<string> {"A","B","C","D"}

        List<List<string>> obList = new List<List<string>>();
        List<string> tst = new List<string>(2);
        foreach (var s in result)
        {
            tst.Add(s);
            if (tst.Count == 2)
            {
                obList.Add(tst);
                tst = new List<string> { s };
            }
        }

【问题讨论】:

  • 如果您不想使用来自链接副本的过于复杂和普遍接受的答案 - 这实际上似乎并没有解决您的问题,即关于复制第二项 -你可以试试这个:var obList = result.Zip(result.Skip(1)).Select(p =&gt; new List&lt;string&gt; { p.First, p.Second }).ToList();

标签: c# .net-core


【解决方案1】:

一种解决方案是使用for 循环迭代结果List,并使用迭代器获取当前元素的范围加上列表中的下一个元素作为新列表

//You would stop the loop at the second to last element in the result list
//That way you don't get a new list with only the last element and in this 
//code block, an index out of range exception the last element would cause 
//the exception as GetRange(i, 2) on the last element would be out of range
for(int i = 0; i < result.Count - 1; i++)
{
   //Grab the range    
   obList.Add(result.GetRange(i, 2).ToList());
}

【讨论】:

  • 嗨!感谢您的回答!但是在第一个列表中使用此解决方案,我将只有 1 个项目
  • @MarcosVarela 我搞砸了GetRange(int32, int32) 方法。我需要将第二个参数作为要返回的项目数,第一个是起始索引。我更新了答案。立即尝试。
猜你喜欢
  • 2018-10-11
  • 1970-01-01
  • 2013-11-24
  • 2010-10-15
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 2016-01-26
  • 2017-11-27
相关资源
最近更新 更多