【问题标题】:Compare each class attribute value using LINQ使用 LINQ 比较每个类属性值
【发布时间】:2016-08-17 04:20:48
【问题描述】:

我有一个下面的课程。我会得到两个对象List<Client> data1List<Client> data2。我想将 data1 和 data2 与每个属性值进行比较。

例如,如果 data1 对象的 LastName=a 和 ClientId=1,..etc 并且如果 data2 列表具有相同的数据集,我想将其推送到另一个列表中。 任何想法,我们如何使用 LINQ/Minimal 代码来实现这一点?

public class Client 
{
    public int ClientId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string Email { get; set; }
}

【问题讨论】:

标签: c# asp.net-mvc linq


【解决方案1】:

使用相交

    List<Client> data1 = new List<Client>();
    List<Client> data2 = new List<Client>();
    List<Client> newlst = new List<Client>();

    Client obj = new Client();
    obj.ClientId = 1;
    obj.LastName = "a";
    obj.FirstName = "n";
    obj.Email = "e";

    data1.Add(obj);
    data2.Add(obj);

    obj = new Client();
    obj.ClientId = 2;
    obj.LastName = "a";
    obj.FirstName = "f";
    obj.Email = "e";

    data1.Add(obj);
    newlst = data1.Intersect(data2).ToList();

【讨论】:

  • 我在我的案例中使用了 Intersect。但这对我不起作用。如果我使用 data1.Intersect(data1) 将起作用。但是,如果我尝试与 data2 相交,它会给我计数 = 0。我确信数据是相等的。我需要用 IEqualityComparer 做些什么吗?
  • 是的,空结果表明默认比较器不足以满足您的目的,因此创建 IEqualityComparer 的实现是可行的方法。
  • @Nam 如果此代码在示例中具有count = 1,它如何给您count = 0。你是不是可能做错了什么? intersect 应该可以工作,但我仍然会实现 IEqualityComparer。
  • 是的,上面的代码给了我count=1,但在我的例子中它总是给我count=0;添加 IEqualityComparer 后给了我正确的值。我赞成这个给我一个想法,以便我能够谷歌并实施 IEqualityComparer 。
【解决方案2】:

我使用了 IEqualityComparer,它用于比较集合和 Intersect 将给出共同值。我已经测试了少数场景的代码。您可以检查所有场景。

希望这段代码会有所帮助。

namespace UnitTestProject
{
    [TestClass]
    public class CompareTwoGenericList
    {
        [TestMethod]
        public void TestMethod1()
        {
            var coll = GetCollectionOne();
            var col2 = GetCollectionTwo();

            //Gives the equal value
            var commonValue = coll.Intersect(col2, new DemoComparer()).ToList();

            //Difference
            var except=coll.Except(col2, new DemoComparer()).ToList();
        }

        public List<Demo> GetCollectionOne()
        {
            List<Demo> demoTest = new List<Demo>()
            {
                new Demo
                {
                    id=1,
                    color="blue",
                },
                new Demo
                {
                    id=2,
                    color="green",
                },
                new Demo
                {
                    id=3,
                    color="red",
                },
            };

            return demoTest;
        }

        public List<Demo> GetCollectionTwo()
        {
            List<Demo> demoTest = new List<Demo>()
            {
                new Demo
                {
                    id=1,
                    color="blue",
                },
                new Demo
                {
                    id=2,
                    color="green",
                },
                new Demo
                {
                    id=4,
                    color="red",
                },
            };

            return demoTest;
        }
    }

    // Custom comparer for the Demo class
    public class DemoComparer : IEqualityComparer<Demo>
    {
        // Products are equal if their color and id are equal.
        public bool Equals(Demo x, Demo y)
        {
            //Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y)) return true;

            //Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;

            //Check whether the demo properties are equal.
            return x.color == y.color && x.id == y.id;
        }

        // If Equals() returns true for a pair of objects
        // then GetHashCode() must return the same value for these objects.

        public int GetHashCode(Demo demo)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(demo, null)) return 0;

            //Get hash code for the color field if it is not null.
            int hashColor = demo.color == null ? 0 : demo.color.GetHashCode();

            //Get hash code for the id field.
            int hashId = demo.id.GetHashCode();

            //Calculate the hash code for the product.
            return hashColor ^ hashId;
        }
    }
}

【讨论】:

    【解决方案3】:

    创建您的新类 ClientView

    public class ClientView{
     public int ClientId { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }
    }
    

    列表 lst = new List();

                    var data = from n in db.client
    
                               select new ClientView()
                               {
                                   ClientId = n.ClientId ,
                                   LastName = n.LastName ,
                                   FirstName = n.FirstName,
    
                               };
                   var data1 = from n in db.client
    
                               select new ClientView()
                               {
                                   ClientId = n.ClientId ,
                                   LastName = n.LastName ,
                                   FirstName = n.FirstName,
    
                               };
                    lst.AddRange(data);
                    lst.AddRange(data1);
    
    List<ClientView> lst1 = new List<ClientView>();
                    foreach (var singlelst in lst)
                    {
    
                        ClientView newClient = new ClientView ();
                        newClient.Id = singlelst.Id;
                        newClient.આપેલ = singlelst.LastName;
                        newClient.આપેલતારીખ = singlelst.FirstName;
                        lst1.Add(newClient);
                    }
    

    【讨论】:

      【解决方案4】:

      试试这个:

      public IEnumerable<PropertyInfo> GetVariance(Client user)
      {
          foreach (PropertyInfo pi in user.GetType().GetProperties()) {
      
              object valueUser = typeof(Client).GetProperty (pi.Name).GetValue (user);
              object valueThis = typeof(Client).GetProperty (pi.Name).GetValue (this);
      
              if (valueUser != null && !valueUser.Equals(valueThis))
                  yield return pi;
      
          }
      }
      
      IEnumerable<PropertyInfo> variances = data1.GetVariance (data2);
      
      foreach (PropertyInfo pi in variances)
            Console.WriteLine (pi.Name);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多