LINQ query with Distinct and Union

前端 未结 4 1552
[愿得一人]
[愿得一人] 2021-01-01 17:29

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

var q1 = ....
         select new MyModel()
         {
             TheData1 = ...
         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 17:49

    Inefficient single line answer with no IEqualityComparerer

    Using MoreLinq source code as inspiration, this will give a unique list:

    Short answer (the OrderBy isn't necessary but if not used the answer comes out as 2,3,6,9,11,4,7,12):

    var concattedUniqueList = theUniqueIDList1.Concat(theUniqueIDList2)
                .GroupBy(f=>f.UniqueID, f=>f).Select(g => g.First()).OrderBy(f=>f.UniqueID);
    

    Complete answer:

    //INPUT
    //theUniqueIDList1 = 2,3,6,9,11 
    //theUniqueIDList2 = 2,4,7,9,12
    //OUTPUT
    //2,3,4,6,7,9,11,12
    public class MyModel
    {
        public string TheData1 { get; set; }
        public string TheData2 { get; set; }
        public int UniqueID { get; set; }
    }
    
    public static void GroupByEx1()
        {
            // Create a list of Models.
            List theUniqueIDList1 =
                new List{  new MyModel { TheData1="Barley",    UniqueID=2 },
                                        new MyModel { TheData1="Boots",     UniqueID=3 },
                                        new MyModel { TheData1="Whiskers",  UniqueID=6 },
                                        new MyModel { TheData1="Daisy",     UniqueID=9 },
                                        new MyModel { TheData1="Preti",     UniqueID=11 } };
            List theUniqueIDList2 =
                new List{  new MyModel { TheData1="Barley",    UniqueID=2 },
                                        new MyModel { TheData1="Henry",     UniqueID=4 },
                                        new MyModel { TheData1="Walsh",     UniqueID=7 },
                                        new MyModel { TheData1="Daisy",     UniqueID=9 },
                                        new MyModel { TheData1="Ugly",  UniqueID=12 } };
            
            var concattedUniqueList = theUniqueIDList1.Concat(theUniqueIDList2)
                .OrderBy(f=>f.UniqueID).GroupBy(f=>f.UniqueID, f=>f).Select(g => g.First());
    
            foreach (var item in concattedUniqueList)
            {
                Console.WriteLine("UniqueId: {0}({1})", item.UniqueID, item.TheData1);
            }
        }
        
    void Main()
    {
        GroupByEx1();               
        //2,3,4,6,7,9,11,12
    }
    

    Note: compared to using an IEqualityComparer for speed - 10000 times for each 698 ns for Concat 100 ns for IEqualityComparer

    developed in LinqPad

提交回复
热议问题