Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq selecting inner values with distinct

Tags:

c#

linq

    class Foo 
    {
        public List<Baz> bazs = new List<Baz> ();
    }

    class Baz
    {
        public List<int> ints = new List<int> ();
    }

    [Test] public void play ()
    {
        var foo = new Foo ();

        foo.bazs = new List<Baz> ()
        {
            new Baz ()
            {
                ints = new List<int> () {1, 2, 3, 4, 5}
            },
            new Baz ()
            {
                ints = new List<int> () {4, 5, 6, 7, 8}
            }
        };

        IEnumerable<int> result = foo.bazs
            .Select (x => x.ints)
            .Distinct ()
            .AsEnumerable ();

        // I'm expecting an IEnumerable<int> 1,2,3,4,5,6,7,8
    }
like image 399
jack-london Avatar asked Dec 28 '25 16:12

jack-london


1 Answers

Simply change your .Select to .SelectMany to flatten the sublists:

.SelectMany (x => x.ints)
like image 91
digEmAll Avatar answered Dec 30 '25 05:12

digEmAll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!