Linq - SelectMany Confusion

前端 未结 4 1093
半阙折子戏
半阙折子戏 2021-01-30 01:42

From what I understand from the documentation of SelectMany, one could use it to produce a (flattened) sequence of a 1-many relationship.

I have following classes

<
4条回答
  •  感情败类
    2021-01-30 02:02

    Though this is an old question, I thought I would improve the excellent answers a little:

    SelectMany returns a list (which may be empty) for each element of the controlling list. Each element in these result lists are enumerated into the expressions' output sequence and so are concatenated into the result. Hence, a' list -> b' list[] -> concatenate -> b' list.

    using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System.Linq;
    using System.Diagnostics;
    namespace Nop.Plugin.Misc.WebServices.Test
    {
        [TestClass]
        public class TestBase
        {
            [TestMethod]
            public void TestMethod1()
            {  //See result in TestExplorer - test output 
                var a = new int[]{7,8};
                var b = new int[]
                        {12,23,343,6464,232,75676,213,1232,544,86,97867,43};
                Func numberHasDigit = 
                        (number
                         , digit) => 
                             ( number.ToString().Contains(digit.ToString()) );
    
                Debug.WriteLine("Unfiltered: All elements of 'b' for each element of 'a'");
                foreach(var l in a.SelectMany(aa => b))
                    Debug.WriteLine(l);
                Debug.WriteLine(string.Empty);
                Debug.WriteLine("Filtered:" +  
                "All elements of 'b' for each element of 'a' filtered by the 'a' element");
                foreach(var l in a.SelectMany(aa => b.Where(bb => numberHasDigit(bb, aa))))
                    Debug.WriteLine(l);
            }
        }
    }
    

提交回复
热议问题