C#将两个列表与重叠数据组合在一起

时间:2016-03-11 01:11:51

标签: c# .net 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"};

我需要一种方法来组合列表,同时防止“重叠”并保留相同的顺序。因此,在上面的示例中,将有一个组合列表:

AA, BB, CC, AA, DD, EE, FF, AA

换句话说,只有 DD,EE,FF和AA 被添加到history列表中。

我一直试图解决这个问题几天,无数的搜索都没有解决问题。任何帮助将不胜感激!

5 个答案:

答案 0 :(得分:5)

这将为您提供您在问题中提到的给定输入集的预期输出:

 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());

.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());  

现在历史记录将包含所需的元素集。

答案 1 :(得分:1)

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> history = new List<string>(){ "AA", "BB", "CC", "AA" };
        List<string> potentialNew = new List<string>(){ "CC", "AA", "DD", "EE", "FF" };
        // make lists equal length

        foreach(var x in history.ConcatOverlap(potentialNew)){
            Console.WriteLine(x);
        }
    }


}

public static class Ext{
    public static IEnumerable<string> ConcatOverlap(this List<string> history, List<string> potentialNew){
        var hleng = history.Count();
        var pleng = potentialNew.Count();
        if(pleng > hleng) history = history.Concat(Enumerable.Range(1, pleng - hleng).Select(x => string.Empty)).ToList();
        if(hleng > pleng) potentialNew = Enumerable.Range(1, hleng - pleng).Select(x => string.Empty).Concat(potentialNew).ToList();


        var zipped = history.Zip(potentialNew, (a,b)=> new {First=a,Next=b, Equal = (a.Equals(b) || string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))});
        var count = 0;
        var max = pleng > hleng ? pleng : hleng;
        Console.WriteLine("Max " + max);
        while(zipped.Any(x => !x.Equal) && count < max - 1){
            count++;
            potentialNew.Insert(0,string.Empty);
            history.Add(string.Empty);
            zipped = history.Zip(potentialNew, (a,b)=> new {First=a,Next=b, Equal = (a.Equals(b) || string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))});
        }
        return zipped.Select(x => string.IsNullOrEmpty(x.First) ? x.Next : x.First);
    }
}

经过多一点考虑后:

public static IEnumerable<T> ConcatOverlap<T>(this IEnumerable<T> head, IEnumerable<T> tail){

    var skip = 0;
    var hLen = head.Count();
    while(head.Skip(skip).Zip(tail, (a,b) => a.Equals(b)).Any(x => !x) && skip < hLen){
        skip++;
    }

    return head.Take(skip).Concat(tail);
}

答案 2 :(得分:1)

var history = new List<string>() { "AA", "BB", "CC", "AA" };
var potentialNew = new List<string>() { "CC", "AA", "DD", "EE", "FF" };

// Get the min. number of items to compare that 2 lists
for (int count = Math.Min(history.Count(), potentialNew.Count()); count >= 0; count--)
{
    // Get the items from the back of history list, and get the items from potential list
    // Compare them by SequenceEqual()
    if (history.Skip(history.Count() - count).Take(count).SequenceEqual(potentialNew.Take(count)))
    {
        // Add the items to the result if found. It must be the greatest common part
        return history.Concat(potentialNew.Skip(count));
    }
}

.Net Fiddle

答案 3 :(得分:0)

这似乎很容易:

List<string> history = new List<string>(){ "AA", "BB", "CC", "AA" };
List<string> potentialNew = new List<string>(){ "CC", "AA", "DD", "EE", "FF", "AA"};

potentialNew.Aggregate(history, (h, p) =>
{
    if (!h.Skip(h.Count - 2).Contains(p))
    {
        h.Add(p);
    }
    return h;
});

结果是history包含:

AA 
BB 
CC 
AA 
DD 
EE 
FF 
AA 

答案 4 :(得分:0)

不确定这在性能方面有多好,但我建立了一个逻辑来实现你想要的。任何人都可以通过调整来使其更清洁。

List<string> history = new List<string>() { "AA", "BB", "CC", "AA" };
List<string> potentialNew = new List<string>() { "CC", "AA", "DD", "EE", "FF", "AA" };

var result = ProcessChatLog(history,potentialNew);
//pass these two list to a function to process the chat log

核心逻辑就在这里。

 public List<string> ProcessChatLog(List<string> history, List<string> potentialNew)
    {
        var lastChat = history.Last();  
        var lastChatIndex = history.Count - 1;
        var allIndexWithLastChat = potentialNew.Select((c, i) => new { chat = c, Index = i })
                                   .Where(x => x.chat == lastChat)
                                   .Select(x => x.Index).Reverse().ToList();       

        List<int> IndexToClear = new List<int>();
        bool overlapFound = false;

        foreach (var index in allIndexWithLastChat)
        {
            if (!overlapFound)
            {
                int hitoryChatIndex = lastChatIndex;
                IndexToClear.Clear();
                for (int i = index; i > -1; i--)
                {
                    if (potentialNew[i] == history[hitoryChatIndex])
                    {
                        IndexToClear.Add(i);
                        if (i == 0)
                        {
                            overlapFound = true;
                            break;
                        }
                        hitoryChatIndex--;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            else
            {
                IndexToClear.Clear();
                break;
            }                             
        }

        if(IndexToClear.Count >0)
        {
            potentialNew.RemoveRange(IndexToClear.Min(), IndexToClear.Count);   
        }

        return history.Concat(potentialNew).ToList();
    }

以下是一些结果

  history = { "AA", "BB", "CC", "AA" }
  potentialNew = { "CC", "AA", "DD", "EE", "FF", "AA"}

  Result = { "AA", "BB","CC", "AA", "DD", "EE", "FF", "AA"}
  history = { "AA", "BB","AA", "CC", "AA" }
  potentialNew = { "AA","CC", "AA", "DD", "EE", "FF", "AA"}

  Result = { "AA", "BB","AA","CC", "AA", "DD", "EE", "FF", "AA"}
  history = { "AA", "BB", "CC", "AA" }
  potentialNew = { "CC", "AA", "CC", "AA", "FF", "AA"}

  Result = { "AA", "BB","CC", "AA", "CC", "AA", "FF", "AA"}
  history = { "AA", "BB", "CC", "AA" }
  potentialNew = {"AA", "CC", "AA", "DD", "EE", "FF", "AA" }

  Result = { "AA", "BB","CC", "AA", "CC", "AA", "DD", "EE", "FF", "AA" }

如果有帮助,请告诉我。

但我仍然说这不是你想要的好的输出。因为如果聊天包含相同的消息20次,并假设你分别在11个和9个项目的2个列表中得到它。现在根据您所需的输出,您将省略所有9个消息新列表作为可能的重复和一个问题。所以我说而不是这个解决方案,解决方案是跟踪聊天记录中传递的消息,并采取措施不在下一个日志中传递这些消息。这样就可以保持逻辑和准确性