SelectMany operator in Linq C#

  • Home
  • Blog
  • SelectMany operator in Linq C#

SelectMany is an important operator in Linq. It takes each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence. You can find out more information about different overload list from the below link.

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx

In this post I am going to explain How it can be really useful when you want to find list related to two entities. Practical example will be like a person can have multiple address and if you want to find list of addresses that are used with person then this SelectMany operator can be really useful.

So for this example First, I have create Address class with Street and Postalvcode property

public class Address
{
    public string Street { get; set; }
    public string PostalCode { get; set; }
}

Now we are going to create Person class which have Name property and A person can have multiple address so address generic list as property like following.

public class Person
{
    public string Name { get; set; }
    public List Addresses { get; set; }
}

Now our both class are ready so I have created classes for data like following.

private static List persons;
public static void CreatePersonData() {

    //Creating Address
    Address address1 = new Address {
                            Street = "Stree1",
                            PostalCode = "38050"
                       };
    Address address2 = new Address { Street = "Stree2", PostalCode = "38050" };
    Address address3 = new Address { Street = "Stree3", PostalCode = "38050" };

    List addresses1 = new List { address1, address2, address3 };
    List addresses2 = new List { address1, address2 };
    List addresses3 = new List { address1, address3 };

    Person person1 = new Person { Addresses = addresses1, Name = "Person1" };
    Person person2 = new Person { Addresses = addresses2, Name = "Person2" };
    Person person3 = new Person { Addresses = addresses3, Name = "Person3" };

    persons = new List { person1, person2, person3 };
}

As you can see I have created 3 address and created 3 address list with various combinations and then I have created 3 persons and added address list to this 3 persons. Now I want to find the addresses those are used in all the person. So I have written following code in main method of console application.

static void Main() {
    CreatePersonData();
    IEnumerable addresses = persons.SelectMany(p => p.Addresses);
    foreach (var address in addresses) {
        Console.WriteLine("Street:{0} PostalCode:{1}", address.Street, address.PostalCode);
    }
}

You can see in the above code there are I ahve written p=>P.address to find all the address associated with person. Let’s run this example and following is output as expected.

You can see it’s very easy. That’s it. Hope you like it. Stay tuned for more…