欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.NET复习笔记-Linq之联合查询示例

程序员文章站 2022-07-04 09:07:29
...
using System;
using System.Collections.Generic;
using System.Linq;

namespace WinningConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<User> userList = InitUserList();
            List<Student> studentList = InitStudentList();

            var result1 = from user in userList
                          join student in studentList on user.ID equals student.UserID
                          where user.ID > 1
                          select new { UserID = user.ID, user.Name, student.ClassName };

            foreach (var item in result1)
            {
                Console.WriteLine("UserID:{0}, Name:{1}, ClassName:{2}", item.UserID, item.Name, item.ClassName);
            }

            Console.ReadKey();
        }

        private static List<User> InitUserList()
        {
            return new List<User>() {

                new User{ ID = 1, Name = "name1", Age = 13 },
                new User{ ID = 2, Name = "name2", Age = 14 },
                new User{ ID = 3, Name = "name3", Age = 15 }
            };
        }

        private static List<Student> InitStudentList()
        {
            return new List<Student>() {
                new Student { ID = 1, UserID = 1, ClassName = "className1" },
                new Student { ID = 2, UserID = 2, ClassName = "className1" },
                new Student { ID = 3, UserID = 3, ClassName = "className2" }
            };
        }
    }

    internal class Student
    {
        internal int ID { get; set; }
        internal int UserID { get; set; }
        internal string ClassName { get; set; }

    }
    
    internal class User
    {
        internal int ID { get; set; }
        internal string Name { get; set; }
        internal int Age { get; set; }
    }
}

/*输出
UserID:2, Name:name2, ClassName:className1
UserID:3, Name:name3, ClassName:className2
*/

  

上一篇: 初识LINQ

下一篇: 第十二章 Proxy