Convert object list to create new object list in CSharp

Description

The following code shows how to convert object list to create new object list.

Example


using System;/*  w  w w. j  av  a 2s .  co m*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Person
{
    public int Age { get; set; }
    public string Name { get; set; }

    List<Person> friends = new List<Person>();
    public List<Person> Friends
    {
        get { return friends; }
    }

    public Person()
    {
    }

    public Person(string name)
    {
        Name = name;
    }
}
class Projection
{
    static void Main()
    {
        List<Person> family = new List<Person>                 
        {
            new Person {Name="H", Age=31},
            new Person {Name="J", Age=31},
            new Person {Name="T", Age=4},
            new Person {Name="W", Age=1}
        };

        var converted = family.ConvertAll(delegate(Person person)
            { return new { person.Name, IsAdult = (person.Age >= 18) }; }
        );

        foreach (var person in converted)
        {
            Console.WriteLine("{0} is an adult? {1}",
                              person.Name, person.IsAdult);
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    LINQ »




Operator
Select
Where
OrderBy
Group
Join
Let
LINQ