LINQ查询使用DISTINCT和联盟联盟、LINQ、DISTINCT

2023-09-03 12:29:30 作者:14.长辞

我现在有2查询将要返回为MyModel名单如下:

I currently have 2 queries that are returning lists of MyModel like this:

var q1 = ....
         select new MyModel()
         {
             TheData1 = ...
             TheData2 = ...
             TheUniqueID = ...
         }

var q2 = ....
         select new MyModel()
         {
             TheData1 = ...
             TheData2 = ...
             TheUniqueID = ...
         }

如果在Q1我有:

TheUniqueID = 2,3,6,9,11 

和第二季度我有:

TheUniqueID = 2,4,7,9,12

如何编写查询,让我得到为MyModel名单,其中

How do write the query so that I get a list of MyModel where

TheUniqueID = 2,3,4,6,7,9,11,12

在换句话说,每个TheUniqueID是present仅一次(即2和9不重复)。

In other words, each TheUniqueID is present only once (ie. 2 and 9 not repeated).

我开始寻找联盟不同,但我想知道如果我需要2个来自陈述或没有。

I started looking at Union and distinct but I'm wondering if I need 2 from statements or not.

任何建议,欢迎。

推荐答案

我觉得frenchie希望为MyModel 的名单后面,而不仅仅是 TheUniqueID

I think frenchie wants a list of MyModel back instead of just the TheUniqueID.

您需要创建一个 MyModelTheUniqueIDComparer 类,并通过它的一个新的实例作为第二个参数为联盟

You need to create a MyModelTheUniqueIDComparer class and pass a new instance of it as a second argument into Union:

class MyModelTheUniqueIDComparer : IEqualityComparer<MyModel>
{
    public bool Equals(MyModel x, MyModel y)
    {
        return x.TheUniqueID == y.TheUniqueID;
    }

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

    public int GetHashCode(MyModel myModel)
    {
        return myModel.TheUniqueID.GetHashCode();
    }
}

然后就可以调用得到的结果:

Then you can call to get the result:

var result = q1.Union(q2, new MyModelTheUniqueIDComparer());

请参阅http://msdn.microsoft.com/en-us/library/bb358407.aspx对于更多的细节。

See http://msdn.microsoft.com/en-us/library/bb358407.aspx for a more details.

更新:

试试这个:

public class A
{
    public string TheData1 { get; set; }
    public string TheData2 { get; set; }
    public string UniqueID { get; set; }
}

public class AComparer : IEqualityComparer<A>
{

    #region IEqualityComparer<A> Members

    public bool Equals(A x, A y)
    {
        return x.UniqueID == y.UniqueID;
    }

    public int GetHashCode(A obj)
    {
        return obj.UniqueID.GetHashCode();
    }

    #endregion
}

和测试这一点:

var listOfA = new List<A>();
var q1 = from a in listOfA
                 select new A()
             {
                 TheData1 = "TestData",
                 TheData2 = "TestData",
                 UniqueID = a.UniqueID
             };

var anotherListOfA = new List<A>();
var q2 = from a in anotherListOfA
                 select new A()
                 {
                     TheData1 = "TestData",
                     TheData2 = "TestData",
                     UniqueID = a.UniqueID
                 };

q1.Union(q2, new AComparer());

请确保您有使用System.Linq的;