Saturday, September 22, 2018

Select & SelectMany in LINQ C#

Select  :: It's select valu from collection
SelectMany :: It's select value from multipe collection.
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> students = new List<Student>{
            new Student {
                Name = "Dhananjay",
                RollNumber ="1" ,
                Subject= new List<string>{"Math","Phy"}},
            new Student {
                Name = "Scott",
                RollNumber ="2" ,
                Subject= new List<string>{"Che","Phy"}},
            new Student {
                Name = "John",
                RollNumber ="3" ,
                Subject= new List<string>{"Hindi","Phy"}}};

            // Reteriving all students with name D 
            var result1 = from r in students
                          where r.Name.StartsWith("D")
                          select r;
            foreach (var r in result1)
            {
                Console.WriteLine(r.Name);
            }

            // Reteriving  the result in Anonymous  class
            var result2 = from r in students
                          select new { r.RollNumber, r.Name };
            foreach (var r in result2)
            {
                Console.WriteLine(r);
            }

            // Reteriving using SelectMany 
            var result3 = from r in students
                          select r;
            foreach (var r in
                result3.SelectMany(Student => Student.Subject))
            {
                Console.WriteLine(r);
            }

            // directly applying  SelectMany 
            var result = students.AsQueryable()
                        .SelectMany(Subject => Subject.Subject);
            foreach (var r in result)
            {
                Console.WriteLine(r);
            }

            Console.Read();
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public string RollNumber { get; set; }
        public List<string> Subject { get; set; }
    }
}

No comments:

Post a Comment

Find the value from array when age is more than 30

 const data = [   { id: 1, name: 'Alice', age: 25 },   { id: 2, name: 'Bob', age: 30 },   { id: 3, name: 'Charlie', ...