chu*_*122 4 .net c# linq list overlapping
如果我有2个字符串列表
List<string> history = new List<string>(){ "AA", "BB", "CC", "AA" };
List<string> potentialNew = new List<string>(){ "CC", "AA", "DD", "EE", "FF", "AA"};
Run Code Online (Sandbox Code Playgroud)
我需要一种方法来组合列表,同时防止"重叠"并保持相同的顺序.因此,在上面的示例中,将有一个组合列表:
AA, BB, CC, AA, DD, EE, FF, AA
Run Code Online (Sandbox Code Playgroud)
换句话说,只有DD,EE,FF和AA被添加到history列表中.
我一直试图解决这个问题几天,无数的搜索都没有解决问题.任何帮助将不胜感激!
如您在问题中提到的,这将为您提供给定输入集的预期输出:
List<string> history = new List<string>() { "AA", "BB", "CC", "AA" };
List<string> potentialNew = new List<string>() { "CC", "AA", "DD", "EE", "FF" };
var result = history.Concat(potentialNew.Where(x => !history.Contains(x)).ToList());
Run Code Online (Sandbox Code Playgroud)
该.Concat()方法允许您连接两个列表.我们从potentialNew第一个列表中不存在的特定项目中提取特定项目,并将它们与第一个列表连接起来.
更新:根据我们的讨论,我得出的结论是,您正在寻找以下内容:
string lastItem = history.Last();
int lastIndexToCheck=history.Count-2,i=0;
for (; i < potentialNew.Count - 1; i++)
{
if (potentialNew[i] == lastItem && potentialNew[i - 1] == history[lastIndexToCheck])
{
break;
}
}
history.AddRange(potentialNew.Skip(i+1).ToList());
Run Code Online (Sandbox Code Playgroud)
现在历史将包含所需的元素集.
| 归档时间: |
|
| 查看次数: |
921 次 |
| 最近记录: |