1. 程式人生 > >C#中使用匿名類和初始化器

C#中使用匿名類和初始化器

程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var pet = new { age = 10, Name = "dog" };
            var students = new List<studentname>{new studentname("hh","hah"),new studentname("di","di")};
            var studentFrom = new List<studentFrom>
            {
                new studentFrom{firstname="hha",city="nsfd"},
                new studentFrom{firstname="di",city="asdf"}
            };
            var joinquery = from s in students
                            join f in studentFrom on s.firstname equals f.firstname
                            select new {firstName = s.firstname,s.lastname,city = f.city};
            foreach(var j in joinquery)
            {
                Console.WriteLine("{0} {1} {2}",j.firstName,j.lastname,j.city);
            }
            Console.ReadLine();
        }
        public class studentname
        {
            public string firstname { get; set; }
            public string lastname{get; set;}
        
            public int ID {get;set;}

            public studentname()
            { }
            public studentname(string first,string last)
            {
                firstname = first;
                lastname = last;
            }
            public override string ToString()
            {
                return firstname + " " + ID;
            }
        }
        public class studentFrom
        {
            public string firstname { get; set; }
            public string city { get; set; }
        }
    }
   
}

執行結果如下:
在這裡插入圖片描述