简体   繁体   English

比较清单 <string> 和清单 <T>

[英]compare List<string> and List<T>

I'm using C# and framework 4.0. 我正在使用C#和Framework 4.0。

I have a list of type string and another list of type class T; 我有一个字符串类型的列表和另一个T类类型的列表;

How can I compare List with a List and save the difference? 如何将列表与列表进行比较并保存差异?

private void simpleButton_Compare_Click(object sender, EventArgs e)
{
    try
    {
        bool Is_Egal = true;                 

        int i = 0;
        foreach (string Od_Scan in Ordre_Scan)
        {
            if (!Outils.Get_Ordre_Donne()[i].NoOrdre.Contains(Od_Scan) && !String.IsNullOrWhiteSpace(Od_Scan))
            {
                Is_Egal = false;
                Temp_Od_Scan.Add(Od_Scan);
            }                    
            i++;
        }

        foreach (Pers_Compare Od_Done in Outils.Get_Ordre_Donne())
        {
            if (!Ordre_Scan.Contains(Od_Done.NoOrdre) && !String.IsNullOrWhiteSpace(Od_Done.NoOrdre))
            {
                Is_Egal = false;
                Temp_Od_Donne.Add(Od_Done);
            }
            else
            {
                Temp_Od_Donne_Egal.Add(Od_Done);
            }
        }

        if (Is_Egal)
        { 
            MessageBox.Show("égalité");
        }
        else
        { 
            MessageBox.Show("PAS égalité"); 
        }

     }
     catch (Exception excThrown)
     {
         MessageBox.Show(excThrown.Message);
     }
 }

and the data : 和数据:

List<string> Ordre_Scan= new List<string> { "azer","qsdf"};

Pers_Compare obj = new Pers_Compare();
obj.Nolv = 1;
obj.Noordre = "qsdf"

Pers_Compare obj2 = new Pers_Compare();
obj2.Nolv = 1;
obj2.Noordre = "wxcv"

List<Pers_Compare> Ordre_Donne = new List<Pers_Compare>();
Ordre_Donne.add(obj);
Ordre_Donne.add(obj2);

And I want to save the data in Ordre_Donne but not in Od_Scan and vice versa. 我想将数据保存在Ordre_Donne中,而不要保存在Od_Scan中,反之亦然。

foreach (string Od_Scan in Temp_Od_Scan)
{
    all item that not found in List A
    -->  wxcv
}

foreach (var Od_Done in Temp_Od_Donne)
{
    all item that not found in List B
    -->   azer
}

The answer given for a slightly different question (comparing a List with another List) seems to me to be a good solution for your issue, they address multiple issues to do with comparisons of lists. 在我看来, 为一个稍有不同的问题(将一个列表与另一个列表进行比较)给出的答案似乎是解决您的问题的好方法,它们解决了与列表比较有关的多个问题。

EDIT: However you should be more specific with your requirements ie what exactly is a 'difference', eg is {1,1,2} and {1,2} the same? 编辑:但是,您应该更具体地满足您的要求,即“差异”到底是什么,例如{1,1,2}和{1,2}是相同的吗?

Here is the answer given the most votes... (included here just encase it gets removed for some reason (as per Bob' suggestion)) 这是票数最高的答案...(包括在其中,以防止由于某些原因(根据鲍勃的建议)将其删除)

" DESCRIPTION : I need to check that they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list. Is there a built-in function that checks this? What if I guarantee that each element appears only once in a list? 说明 :无论它们在列表中的位置如何,我都需要检查它们是否具有相同的元素。每个MyType对象可能在列表上出现多次。是否有内置函数对此进行检查?如果我保证每个元素在列表中仅出现一次?

EDIT: Guys thanks for the answers but I forgot to add something, the number of occurrences of each element should be the same on both lists. 编辑:伙计们感谢您的回答,但我忘了添加一些内容,每个元素的出现次数在两个列表中应该相同。

ANSWER : If you want them to be really equal (ie the same items and the same number of each item), I think that the simplest solution is to sort before comparing: 答案 :如果您希望它们真正相等(即相同的项目,并且每个项目的编号相同),我认为最简单的解决方案是在比较之前进行排序:

Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))

Edit: 编辑:

Here is a solution that performs a bit better (about ten times faster), and only requires IEquatable , not IComparable : 这是一个性能更好的解决方案(大约快十倍),并且只需要IEquatable ,而不需要IComparable

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2) {
  var cnt = new Dictionary<T, int>();
  foreach (T s in list1) {
    if (cnt.ContainsKey(s)) {
      cnt[s]++;
    } else {
      cnt.Add(s, 1);
    }
  }
  foreach (T s in list2) {
    if (cnt.ContainsKey(s)) {
      cnt[s]--;
    } else {
      return false;
    }
  }
  return cnt.Values.All(c => c == 0);
}

Edit 2: 编辑2:

To handle any data type as key (for example nullable types as Frank Tzanabetis pointed out), you can make a version that takes a comparer for the dictionary: 要将任何数据类型作为键来处理(例如,Frank Tzanabetis指出的可为空的类型),可以创建一个使用字典比较器的版本:

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) {
  var cnt = new Dictionary<T, int>(comparer);
  ...

"

  var list1 = Ordre_Donne.Where(o => !Ordre_Scan.Any(s => s == o.Noordre));
  var list2 = Ordre_Scan.Where(s => !Ordre_Donne.Any(o => o.Noordre == s));

You can either implement IComparable on your Pers_Compare class, which will look something like: 您可以在Pers_Compare类上实现IComparable,该类将类似于:

    public int CompareTo(string other)
    {
        return this.Noordre.CompareTo(other);
    }

Or, if you don't have control of the data structure, you could do something like 或者,如果您无法控制数据结构,则可以执行以下操作

var Temp_Od_Donne = from od in Ordre_Donne
                    where !Ordre_Scan.Contains(od.Noordre)
                    select od;

var Temp_Od_Scan = from os in Ordre_Scan
                   where !Ordre_Donne.Select(od => od.Noordre).Contains(os)
                   select os;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM