Create new object from query in CSharp

Description

The following code shows how to create new object from query.

Example


using System;/*from   w ww  . j  a va  2  s . c o m*/
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using System.Linq;

    class Car
    {
        public string PetName;
        public string Color;
        public int Speed;
        public string Make;
        
        public override string ToString()
        {
            return string.Format("Make={0}, Color={1}, Speed={2}, PetName={3}",Make, Color, Speed, PetName);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Car[] myCars = new []{
                new Car{ PetName = "A", Color = "Silver", Speed = 100, Make = "BMW"},
                new Car{ PetName = "B", Color = "Black", Speed = 55, Make = "VW"},
                new Car{ PetName = "C", Color = "White", Speed = 43, Make = "Ford"}
            };
        
            var makesColors = from c in myCars select new {c.Make, c.Color};
            foreach (var o in makesColors)
            {
                Console.WriteLine(o.ToString());
            }

        
        }
    }

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var