C# Linq Inner Join 和Left Join

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

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            List names = new List();
            List addresses = new List();
            names.Add(new StudentNameModel
            {
                StudentID = "1",
                StudentName = "张三"
            });
            names.Add(new StudentNameModel
            {
                StudentID = "2",
                StudentName = "李四"
            });
            names.Add(new StudentNameModel
            {
                StudentID = "3",
                StudentName = "王五"
            });
            addresses.Add(new StudentAddressModel
            {
                StudentID = "1",
                StudentAddress = "浙江"
            });
            addresses.Add(new StudentAddressModel
            {
                StudentID = "2",
                StudentAddress = "江苏"
            });
            #region inner join
            var innerquery = from n in names
                             join a in addresses on n.StudentID equals a.StudentID
                             select new
                             {
                                 n.StudentID,
                                 n.StudentName,
                                 a.StudentAddress
                             };
            var innerrsult = innerquery.ToList();
            #endregion
            #region left join
            var leftquery = from n in names
                            join a in addresses on n.StudentID equals a.StudentID into na
                            from a in na.DefaultIfEmpty()
                            select new
                            {
                                n.StudentID,
                                n.StudentName,
                                StudentAddress = a == null ? "" : a.StudentAddress//判断地址是否存在
                            };
            var leftreuslt = leftquery.ToList();
            #endregion
        }
    }
    class StudentNameModel
    {
        public string StudentID { get; set; }
        public string StudentName { get; set; }
    }
    class StudentAddressModel
    {
        public string StudentID { get; set; }
        public string StudentAddress { get; set; }
    }
}

lambda获取结果指向对象

var leftquery = from n in names
                            join a in addresses on n.StudentID equals a.StudentID into na
                            from a in na.DefaultIfEmpty()
                            select new { n, a };
            var leftreuslt = leftquery.ToList();

 

你可能感兴趣的:(c#)