簡體   English   中英

如何編寫LINQ查詢以僅基於特定屬性檢索不同的記錄?

[英]how do I write LINQ query to retrieve distinct records based on only specific properties?

我有一個對象DataTestplans數組,我嘗試使用所示的LINQ查詢從其中檢索特定DataIDProductID記錄,我當前的查詢具有Distinct() ,它Distinct()了所有提到的5個屬性,如何根據以下內容檢索不同的記錄屬性DataIDTestPlanNameTCIndexListProductID

數據測試計划:

[
    {
    "DataTestPlanID": 0,
    "DataID": 19148,
    "TestPlanName": "string",
    "TCIndexList": "string",
    "ProductID": 2033915
  },
    {
    "DataTestPlanID": 0,
    "DataID": 19148,
    "TestPlanName": "string",
    "TCIndexList": "string",
    "ProductID": 2033915
  },
      {
    "DataTestPlanID": 0,
    "DataID": 19149,
    "TestPlanName": "string",
    "TCIndexList": "string",
    "ProductID": -2642
  }

]

LINQ

            DataTestPlans_DataID_ProductID = DataTestPlans.Where(c => c.DataID == DataID_ProductID_Record.DataID && c.ProductID == DataID_ProductID_Record.ProductID).Distinct();

你可以這樣

DataTestPlans.Where(c => c.DataID == YourInput && c.ProductID == YourInput)
             .GroupBy(x => new {x.DataID,x.TestPlanName,x.TCIndexList,x.ProductID})
             .Select(x => x.First());

有兩種方法可以完成此問題兩種方法都不需要IComparer。 這是一個可以使用的快速示例(我沒有使用您的實際對象,因為這樣更容易解釋):

class Program
{
    static void Main(string[] args)
    {
        var persons = Setup();

        //option 1, can stream, option suggested by Jon Skeet
        //https://stackoverflow.com/a/1300116/897326
        var result1 = persons.
            DistinctBy(m => new {m.FirstName, m.LastName});

        //option 2, cannot stream, but does reference to DistinctBy
        //https://stackoverflow.com/a/4158364/897326
        var result2 = persons.
            GroupBy(m => new { m.FirstName, m.LastName }).
            Select(group => group.First());
    }

    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string Address { get; set; }
    }

    private static List<Person> Setup()
    {
        var p1 = new Person
        {
            FirstName = "John",
            LastName = "Doe",
            Address = "USA"
        };

        var p2 = new Person
        {
            FirstName = "John",
            LastName = "Doe",
            Address = "Canada"
        };

        var p3 = new Person
        {
            FirstName = "Jane",
            LastName = "Doe",
            Address = "Australia"
        };

        var persons = new List<Person>();
        persons.Add(p1);
        persons.Add(p2);
        persons.Add(p3);

        return persons;
    }
}

public static class LinqExtensions
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        HashSet<TKey> knownKeys = new HashSet<TKey>();
        foreach (TSource element in source)
        {
            if (knownKeys.Add(keySelector(element)))
            {
                yield return element;
            }
        }
    }
}

您將必須使用GroupBy() ,這將創建一個IEnumerable<IGrouping<TKey, TElement>> ,您可以對其進行迭代。 您可以使用group.First()或通過組上的某種聚合函數來訪問記錄。

您可以使用多個鏈接的wheres。 如果要進行數據庫調用,請確保它是IQueryable。 下面是一個例子

List<SomeClass> c = new List<SomeClass>();
 var result = c.Where(x => x.ID == 4).Distinct().Where(y => y.Name == "foo").Distinct();

您可以實現IEqualityComparer並在Distinct()方法中使用默認值。 如果您示例實現DataTestPlansComparer ,則可以在以下示例中使用:

DataTestPlans_DataID_ProductID = DataTestPlans.Where(c => c.DataID == DataID_ProductID_Record.DataID && c.ProductID == DataID_ProductID_Record.ProductID).Distinct(new DataTestPlansComparer());

注意,您的自定義比較器應作為參數傳遞給Distinct()方法。

您的情況可以是:

        public class DataTestPlanComparer : IEqualityComparer<DataTestPlan>
        {
            public bool Equals(DataTestPlan x, DataTestPlan y)
            {

                if (Object.ReferenceEquals(x, y)) return true;

                if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                    return false;

                return x.DataID == y.DataID && x.ProductID == y.ProductID;
            }


            public int GetHashCode(DataTestPlan dataTestPlan)
            {
                if (Object.ReferenceEquals(dataTestPlan, null)) return 0;

                int hashDataTestPlanDataID = dataTestPlan.DataID == null ? 0 : dataTestPlan.DataID.GetHashCode();

                int hashDataTestPlanProductID = dataTestPlan.ProductID.GetHashCode();

                return hashDataTestPlanDataID ^ hashDataTestPlanProductID;
            }
        }

請按照MSDN指南實施IEqualityComparer。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM