简体   繁体   English

如何比较.NET中的两个列表

[英]How to compare two lists in .NET

List<Employee> emplist = new List<Employee>();
emplist.Add(new Employee { Name = "Emp_1", BasicSalary = 1000, Id = Guid.NewGuid(), HRA = 100, DA = 10, TotalSalary = 1110 });
emplist.Add(new Employee { Name = "Emp_2", BasicSalary = 1000 * 2, Id = Guid.NewGuid(), HRA = 200, DA = 20, TotalSalary = 2220 });
emplist.Add(new Employee { Name = "Emp_3", BasicSalary = 1000 * 3, Id = Guid.NewGuid(), HRA = 300, DA = 30, TotalSalary = 3330 });

var result = empRep.CallSupportFindAll();

// CollectionAssert.AreEqual(emplist, result);
Assert.AreEqual(emplist, result);
var r1 = result[0];
Assert.AreEqual(r1.Name, emplist[0].Name);
Assert.AreEqual(r1.TotalSalary, emplist[0].TotalSalary);
Assert.AreEqual(r1.BasicSalary, emplist[0].BasicSalary);

I want to compare two lists emplist and result . 我想比较两个列表emplistresult Assert.AreEqual(r1.Name, emplist[0].Name); worked but if we have thousands of records then I need to write thousands of lines. 工作,但如果我们有成千上万的记录,那么我需要写成千上万的行。 so please answer-- for one line code for compare two list... thanks in advance 所以请回答-对于比较两个列表的一个行代码...在此先感谢

If I understand correctly, you simply have two instances of List<Employee> and you want to assert that they are equal. 如果我理解正确,您仅拥有List<Employee>两个实例,并且您想断言它们是相等的。 Ie they have the same number of Employee instances, in the same order, with equal properties. 也就是说,它们具有相同数量的Employee实例,并且顺序相同,并且属性相同。

If so, this has nothing to do with FakeItEasy. 如果是这样,则与FakeItEasy无关。 You simply need a method of performing the assertion. 您只需要执行断言的方法。 Personally I would do this using Fluent Assertions . 我个人将使用Fluent Assertions做到这一点。

result.Should().BeEquivalentTo(emplist);

You can use HashSet<> to compare the two lists. 您可以使用HashSet <>比较两个列表。

First, define an equaliser like this 首先,定义一个这样的均衡器

public class EmployeeComparer : IEqualityComparer<Employee>
    {
        public bool Equals(Employee x, Employee y)
        {
            if (x == null && y == null)
                return true;
            if (x == null || y == null)
                return false;

            //You can implement the equal method as you like. For instance, you may compare by name 
            if (x.Id == y.Id)
                return true;
            return false;
        }

        public int GetHashCode(Employee employee)
        {
            return employee.Id.GetHashCode();
        }
    }

Next, create 2 hash sets based on the input and the result of the method 接下来,根据方法的输入和结果创建2个哈希集

var equaliser = new EmployeeComparer();
HashSet<Employee> inputHashset = new HashSet<Employee>(emplist ,equaliser );
  HashSet<Employee> resultHashset = new HashSet<Employee>(result,equaliser);

Finally, assert the equality of the two sets. 最后,声明两组的相等性。 It means, instead of 这意味着,而不是

 Assert.AreEqual(emplist, result);

Do

 Assert.IsTrue(inputHashset.SetEquals(resultHashset));
  public bool compareTwolist<T>(List<T> lst1,List<T> lst2)
    {

        bool bresult = false;
        if (lst1.GetType() != lst2.GetType())
        {
            return false;
        }

        //if any of the list is null, return false
        if ((lst1 == null && lst2 != null) || (lst2 == null && lst1 != null))
            return false;

        //if count don't match between 2 lists, then return false
        if(lst1.Count != lst2.Count)
            return false;

       foreach (T item in lst1)
       {
           T obj1 = item;
           T obj2 = lst2.ElementAt(lst1.IndexOf(item));
           Type type = typeof(T);

           foreach (System.Reflection.PropertyInfo property in type.GetProperties())
           {
               string obj1Value = string.Empty;
               string obj2Value = string.Empty;

               if (type.GetProperty(property.Name).GetValue(obj1) != null)
                   obj1Value = type.GetProperty(property.Name).GetValue(obj1).ToString();

               if (type.GetProperty(property.Name).GetValue(obj2) != null)
                   obj2Value = type.GetProperty(property.Name).GetValue(obj2).ToString();

               //if any of the property value inside an object in the list didnt match, return false
               if (obj1Value.Trim() != obj2Value.Trim())
               {
                   bresult = false;
                   break;
               }
           }

       }
         return bresult;

 }

yes, I got a solution by creating user define function and pass two lists which we want to compare.. 是的,我通过创建用户定义函数并传递两个我们要比较的列表得到了一个解决方案。

and just check is var a is true or not 只是检查var a是否为真

var a = compareTwolist(empwithoutid, resultwithoutid); var a = compareTwolist(empwithoutid,resultwithoutid); Assert.IsTrue(a); Assert.IsTrue(a);

The comparison methods suggested in the other answers require you to implement equals on all your objects. 其他答案中建议的比较方法要求您对所有对象实施均等。 This doesn't scale well from a maintenance perspective. 从维护的角度来看,这不能很好地扩展。 Also in some tests only subset of fields are to be compared. 同样在某些测试中,仅要比较字段的子集。 This means multiple compare or equals methods to be implemented. 这意味着要实施的多个比较或等于方法。 An alternative is stateprinter which dumps state to a string to compare against. 另一种方法是stateprinter,它将状态转储到字符串中以进行比较。 It can even write and rewrite your asserts for you. 它甚至可以为您编写和重写断言。 See https://github.com/kbilsted/StatePrinter/blob/master/doc/AutomatingUnitTesting.md for more info on automation and https://github.com/kbilsted/StatePrinter/blob/master/doc/TheProblemsWithTraditionalUnitTesting.md for an in depth discussion on problems with unit testing as you are facing now. https://github.com/kbilsted/StatePrinter/blob/master/doc/AutomatingUnitTesting.md的自动化和更多信息https://github.com/kbilsted/StatePrinter/blob/master/doc/TheProblemsWithTraditionalUnitTesting.md为您现在面对的有关单元测试问题的深入讨论。

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

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