Select and SelectMany Operations in LINQ

Source: Internet
Author: User

The work of Select () and SelectMany () generates one or more result values based on the source value. Select () generates a result value for each source value. Therefore, the overall result is a collection that has the same number of elements as the source collection. In contrast,SelectMany () generates a single population result that contains a concatenation sub-collection from each source value. The conversion function passed as a parameter to SelectMany () must return an enumerable sequence of values for each source value. SelectMany () then concatenates these enumerable sequences to create a large sequence.

The following two illustrations illustrate the conceptual differences between the operations of these two methods. In each case, assume that the selector (transform) function selects an array of floral data from each source value.

Describes how Select () returns a collection that has the same number of elements as the source collection.

Describes how SelectMany () concatenates an intermediate array sequence into a final result value that contains each value in each of the intermediate arrays.

code example

The following example comparesSelect ()AndSelectMany ()'s behavior. The code creates a "bouquet" by extracting the first two items from each flower Name list in the source collection. In this example, the conversion function select< ( of <(TSource, TResult>)>) (IEnumerable<(for < (TSource>)>), Func<( of <(TSource, TResult>) >)) The "single value" used is itself a collection of values. This requires additional foreach(Visual Basic is for each) loop to enumerate each string in each subsequence.

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Text.RegularExpressions;
Using System.IO;
Using System.Xml;

Namespace Csharptest
{
Class Bouquet
{
Public list<string> Flowers {get; set;}
}

Class Program
{
static void Main (string[] args)
{
Console.WriteLine ("---------result------------");
Ienumerable<int[]> II = Compute (1, 3, 5, 3);
foreach (int[] i1 in II)
{
foreach (int i2 in i1)
Console.Write (I2);
Console.WriteLine ();
}


Console.WriteLine ("--------string. The Concat connection specifies the String representation of the element in the Object array--------");
Console.WriteLine (String. Concat (New int[] {1000, 22}));
Console.WriteLine ("-----------enumerable.range to generate sequence----------of integers within a specified range");
var list = Enumerable.range (1, 4);
foreach (var item in list)
{
Console.WriteLine (item);
}
Console.WriteLine ("-------Convert a number to ienumerable<int[]> type--------------");
II = from item
In list
where item = = 3
Select New int[] {item};

            foreach (int[] i1 in II)
             {
                 foreach (int i2 in i1)
                     Console.Write (I2);
                Console.WriteLine ();
           }

           //The following is an example of MSDN about select SelectMany
             list<bouquet> bouquets = new list<bouquet> ()  
            {
         new Bouquet {Flowers = new list<string> {"Sunflower", "Daisy", "Daffodil", "Larkspur"}},
&n bsp;       new bouquet{Flowers = new List<string> {"Tulip", "Rose", "Orchid"}},
        new bouquet{Flowers = new List<string> {"Gladiolis", "Lily", " Snapdragon "," Aster "," Protea "},
        new bouquet{Flowers = new list< string> {"Larkspur", "Lilac", "Iris", "Dahlia"}}
   };

Select ***********
ienumerable<list<string>> Query1 = Bouquets. Select (BQ = Bq. Flowers);

SelectMany *********
Ienumerable<string> Query2 = Bouquets. SelectMany (BQ = Bq. Flowers);

Console.WriteLine ("Results by Using Select ():");
Note the extra foreach loop here.
foreach (Ienumerable<string> collection in Query1)
foreach (String item in collection)
Console.WriteLine (item);

Console.WriteLine ("/nresults by Using SelectMany ():");
foreach (string item in Query2)
Console.WriteLine (item);

}

<summary>
Given the sum, Min, Max, and n four positive integers, output all sums that divide sum into n positive integers, where each positive integer k satisfies: Min <= k <= max. These n positive integers can be duplicated, but due to the effect of the additive exchange rate, 1 + 2 and 2 + 1 are repeated splits.
For example, sum = 5,n = 3,min = 1,max = 3, there are only two ways to satisfy a condition:
1 + 1 + 3
1 + 2 + 2
</summary>
<param name= "min" ></param>
<param name= "Max" ></param>
<param name= "Sum" ></param>
<param name= "Count" >n</param>
<returns></returns>
public static ienumerable<int[]> Compute (int min, int max, int sum, int count)
{
var list = enumerable.range (min, max-min + 1);

            if (count = = 1)
                 return
                     from Item
                          in list
                     where item = = SUM
                     Select New int[] {item};

Return list. SelectMany
(
Number = Compute (number, Max, Sum-number, count-1). Select
(
Item = Item. Concat (new int[] {number}). ToArray ()
)
);
}

}
}

Select and SelectMany operations in LINQ

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.