Distinct list of objects based on an arbitrary key in LINQ

前端 未结 5 1407
鱼传尺愫
鱼传尺愫 2020-12-05 05:43

I have some objects:

class Foo {
    public Guid id;
    public string description;
}

var list = new List();
list.Add(new Foo() { id = Guid.Empt         


        
5条回答
  •  难免孤独
    2020-12-05 06:19

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var list = new List();
                list.Add(new Foo() { id = Guid.Empty, description = "empty" });
                list.Add(new Foo() { id = Guid.Empty, description = "empty" });
                list.Add(new Foo() { id = Guid.NewGuid(), description = "notempty" });
                list.Add(new Foo() { id = Guid.NewGuid(), description = "notempty2" });
    
                var unique = from l in list
                             group l by new { l.id, l.description } into g
                             select g.Key;
                foreach (var f in unique)
                    Console.WriteLine("ID={0} Description={1}", f.id,f.description);
                Console.ReadKey(); 
            }
        }
    
        class Foo
        {
            public Guid id;
            public string description;
        }
    }
    

提交回复
热议问题