Difference Between Select and SelectMany

后端 未结 17 1118
长情又很酷
长情又很酷 2020-11-22 05:21

I\'ve been searching the difference between Select and SelectMany but I haven\'t been able to find a suitable answer. I need to learn the differenc

17条回答
  •  太阳男子
    2020-11-22 05:39

    Consider this example :

            var array = new string[2]
            {
                "I like what I like",
                "I like what you like"
            };
            //query1 returns two elements sth like this:
            //fisrt element would be array[5]  :[0] = "I" "like" "what" "I" "like"
            //second element would be array[5] :[1] = "I" "like" "what" "you" "like"
            IEnumerable query1 = array.Select(s => s.Split(' ')).Distinct();
    
            //query2 return back flat result sth like this :
            // "I" "like" "what" "you"
            IEnumerable query2 = array.SelectMany(s => s.Split(' ')).Distinct();
    

    So as you see duplicate values like "I" or "like" have been removed from query2 because "SelectMany" flattens and projects across multiple sequences. But query1 returns sequence of string arrays. and since there are two different arrays in query1 (first and second element), nothing would be removed.

提交回复
热议问题