使用linq动态比较两个对象列表

时间:2016-07-12 06:03:59

标签: c# asp.net linq-to-sql

Click to see the Output:

我有一个员工类

public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Age { get; set; }
        public string Address { get; set; }
        public string ContactNo { get; set; }
    }

并有填充方法填写清单

private static void FillEmployeeList(ref List<Employee> lt1, ref List<Employee> lt2)
        {
            lt1 = new List<Employee> {new Employee{ID=1,Name="Kavya",Age="24",Address="No.1,Nehru Street,Chennai",ContactNo="9874521456"},
            new Employee{ID=2,Name="Ravi",Age="24",Address="Flat No.25/A1,Gandhi Street,Chennai",ContactNo="9658745258"},
            new Employee{ID=3,Name="Lavnya",Age="30",Address="No.12,Shastri nagar,Chennai",ContactNo="5214587896"},
            new Employee{ID=4,Name="Rupa",Age="31",Address="No.23/5,Nehru Street,Chennai",ContactNo="9874521256"},
            new Employee{ID=5,Name="Divya",Age="32",Address="No.1/227,Nehru Street,Chennai",ContactNo="8541256387"},            
            };

            lt2 = new List<Employee> {new Employee{ID=1,Name="Kavya",Age="24",Address="No.1,Nehru Street,Chennai",ContactNo="9874521456"},
            new Employee{ID=2,Name="Ravindran",Age="30",Address="Flat No.25/A1,Gandhi Street,Chennai",ContactNo="9658745258"},
            new Employee{ID=3,Name="Chandru",Age="30",Address="No.12,Shastri nagar,Chennai",ContactNo="5214587896"},
            new Employee{ID=4,Name="Rakesh",Age="32",Address="No.23/5,Nehru Street,Chennai",ContactNo="9874021256"},
            new Employee{ID=5,Name="Suresh",Age="32",Address="No.1/227,Nehru Street,Chennai",ContactNo="8541056387"},
            new Employee{ID=11,Name="Suryakala",Age="28",Address="No.1,Pillayar koil Street,Chennai",ContactNo="9541204782"},
            new Employee{ID=12,Name="Thivya",Age="41",Address="No.42,Ellaiamman koil Street,Chennai",ContactNo="9632140874"},           
            };
        }

比较两个对象列表

protected List<Employee> ListCompare(List<Employee> lt1, List<Employee> lt2)
        {
            FillEmployeeList(ref lt1, ref lt2);
            List<Employee> lst = new List<Employee>();

            if (lt1.Count > 0 && lt2.Count > 0)
            {
                // Displaying Matching Records from List1 and List2 by ID

                var result = (from l1 in lt1
                              join l2 in lt2
                              on l1.ID equals l2.ID
                              orderby l1.ID
                              select new
                              {

                                  ID = l1.ID,
                                  Name = (l1.Name == l2.Name) ? "$" : (l2.Name + " (Modified)"),
                                  Age = (l1.Age == l2.Age) ? "$" : (l2.Age + " (Modified)"),
                                  Address = (l1.Address == l2.Address) ? "$" : (l2.Address + " (Modified)"),
                                  ContactNo = (l1.ContactNo == l2.ContactNo) ? "$" : (l2.ContactNo + " (Modified)")
                              }).ToList();

                // Displaying Records from List1 which is not in List2
                var result1 = from l1 in lt1
                              where !(from l2 in lt2
                                      select l2.ID).Contains(l1.ID)
                              orderby l1.ID
                              select new
                              {
                                  ID = l1.ID,
                                  Name = " Deleted",
                                  Age = " Deleted",
                                  Address = " Deleted",
                                  ContactNo = " Deleted"
                              };

                // Displaying Records from List1 which is not in List2
                var result2 = from l1 in lt2
                              where !(from l2 in lt1
                                      select l2.ID).Contains(l1.ID)
                              orderby l1.ID
                              select new
                              {
                                  ID = l1.ID,
                                  Name = l1.Name + " (Added)",
                                  Age = l1.Age + " (Added)",
                                  Address = l1.Address + " (Added)",
                                  ContactNo = l1.ContactNo + " (Added)"
                              };

                var res1 = result.Concat(result1).Concat(result2);

                foreach (var item in res1)
                {
                    Employee emp = new Employee();
                    //Response.Write(item + "<br/>");
                    emp.ID = item.ID;
                    emp.Name = item.Name;
                    emp.Age = item.Age;
                    emp.Address = item.Address;
                    emp.ContactNo = item.ContactNo;
                    lst.Add(emp);
                }
            }
            return lst;
        }

这里我调用compareList方法并返回结果并将其显示在html表中。

List<Employee> lt1 = new List<Employee>();
                List<Employee> lt2 = new List<Employee>();
                List<Employee> resultset = new List<Employee>();
                //string value = "ID";
                StringBuilder htmlTable = new StringBuilder();
                htmlTable.Append("<table border='1'>");
                htmlTable.Append("<tr><th>ID</th><th>Name</th><th>Age</th><th>Address</th><th>ContactNo</th></tr>");
                resultset = ListCompare(lt1, lt2);
                foreach(var item in resultset)
                {
                    htmlTable.Append("<tr>");
                    htmlTable.Append("<td>" + item.ID + "</td>");
                    htmlTable.Append("<td>" + item.Name + "</td>");
                    htmlTable.Append("<td>" + item.Age + "</td>");
                    htmlTable.Append("<td>" + item.Address + "</td>");
                    htmlTable.Append("<td>" + item.ContactNo + "</td>");
                    htmlTable.Append("</tr>");
                }
                htmlTable.Append("</table>");
                PlaceHolder1.Controls.Add(new Literal { Text = htmlTable.ToString() });

我的问题是如何推广这种编码。我可能有任何课程(如员工或学生)。我想要编码只是我将两个对象列表传递给CompareMethod(比较方法我将传递任何类型的对象列表),这将返回列表作为结果。如何进行,请给出任何想法。

2 个答案:

答案 0 :(得分:0)

您可以按以下方式创建比较方法:

protected List<TResult> ListCompare<TKey, TInput, TResult>(List<TInput> lt1, List<TInput> lt2, Func<TInput, TKey> key,  Func<TInput, TInput, TResult> modified, Func<TInput, TResult> added, Func<TInput, TResult> deleted)
{
    // Displaying Matching Records from List1 and List2 by ID
    var matchingEmployees = lt1.Join(lt2, key, key, modified);

    // Displaying Records from List1 which is not in List2
    var lt1NotInlt2 = lt1
          .Where(e1 => !lt2.Any(e2 => key(e2).Equals(key(e1))))
          .Select(deleted);

    // Displaying Records from List2 which is not in List1
    var lt2NotInlt1 = lt2
          .Where(e2 => !lt1.Any(e1 => key(e1).Equals(key(e2))))
          .Select(added);

    return matchingEmployees.Concat(lt1NotInlt2).Concat(lt2NotInlt1).ToList();
}

如果您不想使用密钥,那么您的比较方法应该如下所示,您的类应该实现Equals方法:

protected List<TResult> ListCompare<TInput, TResult>(List<TInput> lt1, List<TInput> lt2, Func<TInput, TInput, TResult> modified, Func<TInput, TResult> added, Func<TInput, TResult> deleted)
{
    // Displaying Matching Records from List1 and List2 by ID
    var matchingEmployees = lt1
        .Where(e1 => lt2.Any(e2 => e2.Equals(e1)))
        .Select(e1 =>
        {
            var e2 = lt2.First(e => e.Equals(e1));

            return modified(e1, e2);
        });

    // Displaying Records from List1 which is not in List2
    var lt1NotInlt2 = lt1
        .Where(e1 => !lt2.Any(e2 => e2.Equals(e1)))
        .Select(deleted);

    // Displaying Records from List2 which is not in List1
    var lt2NotInlt1 = lt2
        .Where(e2 => !lt1.Any(e1 => e1.Equals(e2)))
        .Select(added);

    return matchingEmployees.Concat(lt1NotInlt2).Concat(lt2NotInlt1).ToList();
}

然后你可以像这样调用比较方法:

var result = ListCompare<int, Employee, Employee>(
    lt1,
    lt2,
    e => e.ID,
    (e1, e2) => new Employee
    {
        ID = e1.ID,
        Name = (e1.Name == e2.Name) ? "$" : (e2.Name + " (Modified)"),
        Age = (e1.Age == e2.Age) ? "$" : (e2.Age + " (Modified)"),
        Address = (e1.Address == e2.Address) ? "$" : (e2.Address + " (Modified)"),
        ContactNo = (e1.ContactNo == e2.ContactNo) ? "$" : (e2.ContactNo + " (Modified)")
     },
     e => new Employee
     {
          ID = e.ID,
          Name = e.Name + " (Added)",
          Age = e.Age + " (Added)",
          Address = e.Address + " (Added)",
          ContactNo = e.ContactNo + " (Added)"
      },
      e => new Employee
      {
          ID = e.ID,
          Name = " Deleted",
          Age = " Deleted",
          Address = " Deleted",
          ContactNo = " Deleted"
      });

答案 1 :(得分:0)

如果你对收藏平等感兴趣,我想建议下一步:

  

通过使用指定的IEqualityComparer比较它们的元素来确定两个序列是否相等。 MSDN

  

验证两个指定的集合是否相同。如果集合不相等,则断言失败。 MSDN

  

产生两个序列的集合差异。 MSDN