LINQ的左外连接


538

如何在不使用join-on-equals-into子句的情况下在C#LINQ中对对象执行左外部联接?有什么办法可以使用where子句吗?正确的问题:因为内部联接很容易,我有这样的解决方案

List<JoinPair> innerFinal = (from l in lefts from r in rights where l.Key == r.Key
                             select new JoinPair { LeftId = l.Id, RightId = r.Id})

但是对于左外部联接,我需要一个解决方案。我的是这样的,但没有用

List< JoinPair> leftFinal = (from l in lefts from r in rights
                             select new JoinPair { 
                                            LeftId = l.Id, 
                                            RightId = ((l.Key==r.Key) ? r.Id : 0
                                        })

JoinPair是一个类:

public class JoinPair { long leftId; long rightId; }

2
您能举一个您要达到的目标的例子吗?
jeroenh,2010年

正常的左外部连接是这样的:var a =来自bb中b的连接加入b.bbbbb中cc中的c等于从dd中d中c.ccccc到dd。DefaultIfEmpty()选择b.sss; 我的问题是否有任何方法可以使用join-on-equals-into子句来完成,例如var a = from bb中的b in from cc中的cc,其中b.bbb == c.cccc ...等等。 。
玩具

1
当然有,但是您应该发布一个已有代码示例,以便人们可以为您提供更好的答案
懒惰2010年

我一直在寻找“左排除 ”联接(并且我将其与“外部”的概念混淆了)。这个答案更接近我想要的。
红豌豆

Answers:


597

如上所述:

101个LINQ样本-左外连接

var q =
    from c in categories
    join p in products on c.Category equals p.Category into ps
    from p in ps.DefaultIfEmpty()
    select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };

7
我正在尝试相同的操作,但是在join运算符上遇到错误,该错误表示“ join子句中的表达式之一的类型不正确。”
Badhon Jain

3
@jain如果您的类型不同,则连接将不起作用。因此,您的密钥可能具有不同的数据类型。例如,两个键都是int吗?
Yooakim 2014年

2
Ja那教的解决方案是什么?我也遇到相同的错误,我的情况也一样。
桑迪普2014年

1
@Sandeep检查您加入钥匙的位置。假设如果它们的类型为string和int,则只需将string键转换为int。
Ankit


546

如果使用数据库驱动的LINQ提供程序,则可以这样编写可读性更高的左外部联接:

from maintable in Repo.T_Whatever 
from xxx in Repo.T_ANY_TABLE.Where(join condition).DefaultIfEmpty()

如果您省略,DefaultIfEmpty()则将具有内部联接。

采取公认的答案:

  from c in categories
    join p in products on c equals p.Category into ps
    from p in ps.DefaultIfEmpty()

这种语法非常令人困惑,当您想离开联接MULTIPLE表时,不清楚它是如何工作的。

注意
应该注意的from alias in Repo.whatever.Where(condition).DefaultIfEmpty()是,它与外部应用程序/ left-join-lateral相同,只要您不引入每行,任何(体面的)数据库优化器都可以完全将其转换为左连接-值(也称为实际外部适用)。不要在Linq-2-Objects中执行此操作(因为使用Linq-to-Objects时没有DB优化器)。

详细的例子

var query2 = (
    from users in Repo.T_User
    from mappings in Repo.T_User_Group
         .Where(mapping => mapping.USRGRP_USR == users.USR_ID)
         .DefaultIfEmpty() // <== makes join left join
    from groups in Repo.T_Group
         .Where(gruppe => gruppe.GRP_ID == mappings.USRGRP_GRP)
         .DefaultIfEmpty() // <== makes join left join

    // where users.USR_Name.Contains(keyword)
    // || mappings.USRGRP_USR.Equals(666)  
    // || mappings.USRGRP_USR == 666 
    // || groups.Name.Contains(keyword)

    select new
    {
         UserId = users.USR_ID
        ,UserName = users.USR_User
        ,UserGroupId = groups.ID
        ,GroupName = groups.Name
    }

);


var xy = (query2).ToList();

与LINQ 2 SQL一起使用时,它将很好地转换为以下非常清晰的SQL查询:

SELECT 
     users.USR_ID AS UserId 
    ,users.USR_User AS UserName 
    ,groups.ID AS UserGroupId 
    ,groups.Name AS GroupName 
FROM T_User AS users

LEFT JOIN T_User_Group AS mappings
   ON mappings.USRGRP_USR = users.USR_ID

LEFT JOIN T_Group AS groups
    ON groups.GRP_ID == mappings.USRGRP_GRP

编辑:

有关更复杂的示例,另请参见“ 将SQL Server查询转换为Linq查询 ”。

另外,如果要在Linq-2-Objects中进行操作(而不是Linq-2-SQL),则应采用老式的方法(因为LINQ to SQL可以正确地将其转换为联接操作,但是在对象上使用此方法强制进行全面扫描,并且不利用索引搜索,但是...):

    var query2 = (
    from users in Repo.T_Benutzer
    join mappings in Repo.T_Benutzer_Benutzergruppen on mappings.BEBG_BE equals users.BE_ID into tmpMapp
    join groups in Repo.T_Benutzergruppen on groups.ID equals mappings.BEBG_BG into tmpGroups
    from mappings in tmpMapp.DefaultIfEmpty()
    from groups in tmpGroups.DefaultIfEmpty()
    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);

21
这个答案实际上是有帮助的。感谢您实际提供了可以理解的语法。
克里斯·马里西克

3
WTB NHibernate兼容的LINQ查询... :)
mxmissile 2014年

30
LINQ to SQL可以将其正确转换为联接操作。但是,在对象上使用此方法会强制进行全面扫描,这就是为什么官方文档提供了可以利用哈希值对索引进行搜索的组联接解决方案的原因。
塔米尔丹妮

3
我认为,显式语法joinwhere其后的语法更具可读性和清晰性DefaultIfEmpty
FindOut_Quran 2015年

1
@ user3441905:只要您必须将表a与表b连接起来,就可以了。但是只要您拥有的不止于此,那就不会了。但是,即使只有2张桌子,我也认为它过于冗长。流行观点似乎也对您不利,因为当最高答案已经有90多个投票时,此答案从0开始。
Stefan Steiger 2015年

131

使用lambda表达式

db.Categories    
  .GroupJoin(db.Products,
      Category => Category.CategoryId,
      Product => Product.CategoryId,
      (x, y) => new { Category = x, Products = y })
  .SelectMany(
      xy => xy.Products.DefaultIfEmpty(),
      (x, y) => new { Category = x.Category, Product = y })
  .Select(s => new
  {
      CategoryName = s.Category.Name,     
      ProductName = s.Product.Name   
  });

8
Join和GroupJoin都不真正支持左联接。使用GroupJoin的技巧是,您可以具有空组,然后将这些空组转换为空值。DefaultIfEmpty只是这样做,这意味着Enumerable.Empty<Product>.DefaultIfEmpty()将返回一个具有单个值的IEnumerable default(Product)
塔米尔丹妮

61
所有这些执行左连接?
FindOut_Quran 2015年

7
谢谢你!那里没有太多的lambda表达式示例,这对我有用。
Johan Henkens '16

1
感谢您的回答。它产生了与我多年来写的原始SQL LEFT OUTER JOIN最接近的东西
John Gathogo

1
确实不需要最后一个Select(),可以将SelectMany()中的anon obj重构为相同的输出。另一个想法是测试y的null以模拟更接近的LEFT JOIN等价。
丹尼·雅各布

46

现在作为扩展方法:

public static class LinqExt
{
    public static IEnumerable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TKey> leftKey, Func<TRight, TKey> rightKey,
        Func<TLeft, TRight, TResult> result)
    {
        return left.GroupJoin(right, leftKey, rightKey, (l, r) => new { l, r })
             .SelectMany(
                 o => o.r.DefaultIfEmpty(),
                 (l, r) => new { lft= l.l, rght = r })
             .Select(o => result.Invoke(o.lft, o.rght));
    }
}

像通常使用join一样使用:

var contents = list.LeftOuterJoin(list2, 
             l => l.country, 
             r => r.name,
            (l, r) => new { count = l.Count(), l.country, l.reason, r.people })

希望这可以节省您一些时间。


44

看一下这个例子。此查询应该工作:

var leftFinal = from left in lefts
                join right in rights on left equals right.Left into leftRights
                from leftRight in leftRights.DefaultIfEmpty()
                select new { LeftId = left.Id, RightId = left.Key==leftRight.Key ? leftRight.Id : 0 };

3
可以r在SELECT子句中使用连接到后进行访问?
Farhad Alizadeh Noori 2014年

@FarhadAlizadehNoori是的,可以。
Po-ta-toe

作者可能打算r在第二from个子句中重新使用。即,from r in lrs.DefaultIfEmpty()否则该查询没有多大意义,并且可能由于r没有上下文进行选择而甚至无法编译。
Saeb Amini

@Devart,当我阅读您的查询时,它使我想起Clockwise了约翰·克莱斯(John Cleese)的电影,哈哈。
Matas Vaitkevicius

1
从左到右,到在leftRights中的权利在左边,在左边,在左边,在右边,在右边,在左边,在右边... left rights ...哎呀...在LINQ中使用LEFT OUTER JOIN的语法确实不清楚,但是这些名称确实使它更加不清楚。
Mike Gledhill

19

通过扩展方法实现左外部联接的实现看起来像

public static IEnumerable<Result> LeftJoin<TOuter, TInner, TKey, Result>(
  this IEnumerable<TOuter> outer, IEnumerable<TInner> inner
  , Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector
  , Func<TOuter, TInner, Result> resultSelector, IEqualityComparer<TKey> comparer)
  {
    if (outer == null)
      throw new ArgumentException("outer");

    if (inner == null)
      throw new ArgumentException("inner");

    if (outerKeySelector == null)
      throw new ArgumentException("outerKeySelector");

    if (innerKeySelector == null)
      throw new ArgumentException("innerKeySelector");

    if (resultSelector == null)
      throw new ArgumentException("resultSelector");

    return LeftJoinImpl(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer ?? EqualityComparer<TKey>.Default);
  }

  static IEnumerable<Result> LeftJoinImpl<TOuter, TInner, TKey, Result>(
      IEnumerable<TOuter> outer, IEnumerable<TInner> inner
      , Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector
      , Func<TOuter, TInner, Result> resultSelector, IEqualityComparer<TKey> comparer)
  {
    var innerLookup = inner.ToLookup(innerKeySelector, comparer);

    foreach (var outerElment in outer)
    {
      var outerKey = outerKeySelector(outerElment);
      var innerElements = innerLookup[outerKey];

      if (innerElements.Any())
        foreach (var innerElement in innerElements)
          yield return resultSelector(outerElment, innerElement);
      else
        yield return resultSelector(outerElment, default(TInner));
     }
   }

然后,结果选择器必须处理null元素。Fx。

   static void Main(string[] args)
   {
     var inner = new[] { Tuple.Create(1, "1"), Tuple.Create(2, "2"), Tuple.Create(3, "3") };
     var outer = new[] { Tuple.Create(1, "11"), Tuple.Create(2, "22") };

     var res = outer.LeftJoin(inner, item => item.Item1, item => item.Item1, (it1, it2) =>
     new { Key = it1.Item1, V1 = it1.Item2, V2 = it2 != null ? it2.Item2 : default(string) });

     foreach (var item in res)
       Console.WriteLine(string.Format("{0}, {1}, {2}", item.Key, item.V1, item.V2));
   }

4
但是,这只是 LINQ对对象的一种选择,并且不能将查询转换为任何查询提供程序,这是此操作最常见的用例。
2014年

13
但是问题是“如何在C#LINQ中对对象执行左外部联接...”
Bertrand

12

看这个例子

class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
}

class Pet
{
    public string Name { get; set; }
    public Person Owner { get; set; }
}

public static void LeftOuterJoinExample()
{
    Person magnus = new Person {ID = 1, FirstName = "Magnus", LastName = "Hedlund"};
    Person terry = new Person {ID = 2, FirstName = "Terry", LastName = "Adams"};
    Person charlotte = new Person {ID = 3, FirstName = "Charlotte", LastName = "Weiss"};
    Person arlene = new Person {ID = 4, FirstName = "Arlene", LastName = "Huff"};

    Pet barley = new Pet {Name = "Barley", Owner = terry};
    Pet boots = new Pet {Name = "Boots", Owner = terry};
    Pet whiskers = new Pet {Name = "Whiskers", Owner = charlotte};
    Pet bluemoon = new Pet {Name = "Blue Moon", Owner = terry};
    Pet daisy = new Pet {Name = "Daisy", Owner = magnus};

    // Create two lists.
    List<Person> people = new List<Person> {magnus, terry, charlotte, arlene};
    List<Pet> pets = new List<Pet> {barley, boots, whiskers, bluemoon, daisy};

    var query = from person in people
        where person.ID == 4
        join pet in pets on person equals pet.Owner  into personpets
        from petOrNull in personpets.DefaultIfEmpty()
        select new { Person=person, Pet = petOrNull}; 



    foreach (var v in query )
    {
        Console.WriteLine("{0,-15}{1}", v.Person.FirstName + ":", (v.Pet == null ? "Does not Exist" : v.Pet.Name));
    }
}

// This code produces the following output:
//
// Magnus:        Daisy
// Terry:         Barley
// Terry:         Boots
// Terry:         Blue Moon
// Charlotte:     Whiskers
// Arlene:

现在,include elements from the left即使该元素has no matches in the right,我们也可以检索,Arlene即使他在右侧没有匹配项

这是参考

如何:执行左外部联接(C#编程指南)


输出应为:Arlene:不存在
user1169587 '18

10

这是一般形式(已在其他答案中提供)

var c =
    from a in alpha
    join b in beta on b.field1 equals a.field1 into b_temp
    from b_value in b_temp.DefaultIfEmpty()
    select new { Alpha = a, Beta = b_value };

但是,这里有一个解释,我希望它将阐明这实际上意味着什么!

join b in beta on b.field1 equals a.field1 into b_temp

本质上创建了一个单独的结果集b_temp,该结果集实际上为右侧的条目(“ b”中的条目)包含空的“行”。

然后下一行:

from b_value in b_temp.DefaultIfEmpty()

..迭代该结果集,在右侧设置“行”的默认null值,并将右侧行连接的结果设置为“ b_value”的值(即,右侧的值)如果有匹配的记录,则为空;如果没有,则为“ null”)。

现在,如果右侧是单独的LINQ查询的结果,它将由匿名类型组成,这些匿名类型只能是“某物”或“空”。但是,如果它是可枚举的(例如,列表-MyObjectB是具有2个字段的类),则可以具体说明将哪些默认“空”值用于其属性:

var c =
    from a in alpha
    join b in beta on b.field1 equals a.field1 into b_temp
    from b_value in b_temp.DefaultIfEmpty( new MyObjectB { Field1 = String.Empty, Field2 = (DateTime?) null })
    select new { Alpha = a, Beta_field1 = b_value.Field1, Beta_field2 = b_value.Field2 };

这样可确保'b'本身不为null(但可以使用您指定的默认null值将其属性设置为null),并且可以检查b_value的属性而不会获取b_value的空引用异常。请注意,对于可为空的DateTime,必须在(DefaultIfEmpty)规范中将(DateTime?)类型(即“可为空的DateTime”)指定为null的“类型”(这还将适用于非“本机”类型) '可为null,例如double,float)。

您可以通过简单地链接以上语法来执行多个左外部联接。


1
b_value来自哪里?
杰克·弗雷泽

9

如果您需要联接两个以上的表,请参见以下示例:

from d in context.dc_tpatient_bookingd
join bookingm in context.dc_tpatient_bookingm 
     on d.bookingid equals bookingm.bookingid into bookingmGroup
from m in bookingmGroup.DefaultIfEmpty()
join patient in dc_tpatient
     on m.prid equals patient.prid into patientGroup
from p in patientGroup.DefaultIfEmpty()

参考:https : //stackoverflow.com/a/17142392/2343


4

扩展方法,类似于使用Join语法的左连接

public static class LinQExtensions
{
    public static IEnumerable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
        this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, 
        Func<TOuter, TKey> outerKeySelector, 
        Func<TInner, TKey> innerKeySelector, 
        Func<TOuter, TInner, TResult> resultSelector)
    {
        return outer.GroupJoin(
            inner, 
            outerKeySelector, 
            innerKeySelector,
            (outerElement, innerElements) => resultSelector(outerElement, innerElements.FirstOrDefault()));
    }
}

只是在.NET core中编写的,它似乎可以按预期工作。

小测试:

        var Ids = new List<int> { 1, 2, 3, 4};
        var items = new List<Tuple<int, string>>
        {
            new Tuple<int, string>(1,"a"),
            new Tuple<int, string>(2,"b"),
            new Tuple<int, string>(4,"d"),
            new Tuple<int, string>(5,"e"),
        };

        var result = Ids.LeftJoin(
            items,
            id => id,
            item => item.Item1,
            (id, item) => item ?? new Tuple<int, string>(id, "not found"));

        result.ToList()
        Count = 4
        [0]: {(1, a)}
        [1]: {(2, b)}
        [2]: {(3, not found)}
        [3]: {(4, d)}

4

这是一个使用方法语法的相当容易理解的版本:

IEnumerable<JoinPair> outerLeft =
    lefts.SelectMany(l => 
        rights.Where(r => l.Key == r.Key)
              .DefaultIfEmpty(new Item())
              .Select(r => new JoinPair { LeftId = l.Id, RightId = r.Id }));

3

共有三个表:人员,学校和人员学校,这些人员将人员与他们就读的学校联系起来。在人员_学校表中没有对id = 6的人员的引用。但是,id = 6的人会出现在结果左联合网格中。

List<Person> persons = new List<Person>
{
    new Person { id = 1, name = "Alex", phone = "4235234" },
    new Person { id = 2, name = "Bob", phone = "0014352" },
    new Person { id = 3, name = "Sam", phone = "1345" },
    new Person { id = 4, name = "Den", phone = "3453452" },
    new Person { id = 5, name = "Alen", phone = "0353012" },
    new Person { id = 6, name = "Simon", phone = "0353012" }
};

List<School> schools = new List<School>
{
    new School { id = 1, name = "Saint. John's school"},
    new School { id = 2, name = "Public School 200"},
    new School { id = 3, name = "Public School 203"}
};

List<PersonSchool> persons_schools = new List<PersonSchool>
{
    new PersonSchool{id_person = 1, id_school = 1},
    new PersonSchool{id_person = 2, id_school = 2},
    new PersonSchool{id_person = 3, id_school = 3},
    new PersonSchool{id_person = 4, id_school = 1},
    new PersonSchool{id_person = 5, id_school = 2}
    //a relation to the person with id=6 is absent
};

var query = from person in persons
            join person_school in persons_schools on person.id equals person_school.id_person
            into persons_schools_joined
            from person_school_joined in persons_schools_joined.DefaultIfEmpty()
            from school in schools.Where(var_school => person_school_joined == null ? false : var_school.id == person_school_joined.id_school).DefaultIfEmpty()
            select new { Person = person.name, School = school == null ? String.Empty : school.name };

foreach (var elem in query)
{
    System.Console.WriteLine("{0},{1}", elem.Person, elem.School);
}

尽管这可能是问题的答案,但请提供您答案的一些解释:)
Amir

2

与内部和左外部联接的LINQ语法相比,这是一种SQL语法。左外连接:

http://www.ozkary.com/2011/07/linq-to-entity-inner-and-left-joins.html

“下面的示例在产品和类别之间进行了组联接。本质上是左联接。即使类别表为空,in表达式也会返回数据。要访问类别表的属性,我们现在必须从可枚举的结果中进行选择通过在catList.DefaultIfEmpty()语句中添加from cl。


1

在linq C#中执行左外部联接//在左外部联接中执行

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Child
{
    public string Name { get; set; }
    public Person Owner { get; set; }
}
public class JoinTest
{
    public static void LeftOuterJoinExample()
    {
        Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
        Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
        Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
        Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };

        Child barley = new Child { Name = "Barley", Owner = terry };
        Child boots = new Child { Name = "Boots", Owner = terry };
        Child whiskers = new Child { Name = "Whiskers", Owner = charlotte };
        Child bluemoon = new Child { Name = "Blue Moon", Owner = terry };
        Child daisy = new Child { Name = "Daisy", Owner = magnus };

        // Create two lists.
        List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
        List<Child> childs = new List<Child> { barley, boots, whiskers, bluemoon, daisy };

        var query = from person in people
                    join child in childs
                    on person equals child.Owner into gj
                    from subpet in gj.DefaultIfEmpty()
                    select new
                    {
                        person.FirstName,
                        ChildName = subpet!=null? subpet.Name:"No Child"
                    };
                       // PetName = subpet?.Name ?? String.Empty };

        foreach (var v in query)
        {
            Console.WriteLine($"{v.FirstName + ":",-25}{v.ChildName}");
        }
    }

    // This code produces the following output:
    //
    // Magnus:        Daisy
    // Terry:         Barley
    // Terry:         Boots
    // Terry:         Blue Moon
    // Charlotte:     Whiskers
    // Arlene:        No Child

https://dotnetwithhamid.blogspot.in/


1

我想补充一点,如果您获得MoreLinq扩展名,那么现在就支持均质和异质左联接

http://morelinq.github.io/2.8/ref/api/html/Overload_MoreLinq_MoreEnumerable_LeftJoin.htm

例:

//Pretend a ClientCompany object and an Employee object both have a ClientCompanyID key on them

return DataContext.ClientCompany
    .LeftJoin(DataContext.Employees,                         //Table being joined
        company => company.ClientCompanyID,                  //First key
        employee => employee.ClientCompanyID,                //Second Key
        company => new {company, employee = (Employee)null}, //Result selector when there isn't a match
        (company, employee) => new { company, employee });   //Result selector when there is a match

编辑:

回想起来,这可能有效,但由于morelinq并未将查询转换为SQL,因此它将IQueryable转换为IEnumerable。

您可以改为使用GroupJoin,如此处所述:https : //stackoverflow.com/a/24273804/4251433

这将确保它保持为IQueryable,以备日后需要对其进行进一步的逻辑操作时使用。


1

简单的方法是使用Let关键字。这对我有用。

from AItem in Db.A
Let BItem = Db.B.Where(x => x.id == AItem.id ).FirstOrDefault() 
Where SomeCondition
Select new YourViewModel
{
    X1 = AItem.a,
    X2 = AItem.b,
    X3 = BItem.c
}

这是左连接的模拟。如果B表中的每个项目都与A项目不匹配,则BItem返回null


0

如果您需要加入并过滤某些内容,则可以在加入之外进行。创建集合后即可进行过滤。

在这种情况下,如果我在联接条件下执行此操作,则会减少返回的行。

使用三元条件 (= n == null ? "__" : n.MonDayNote,)

  • 如果对象是null(因此没有匹配项),则返回后面的内容?__, 在这种情况下。

  • 否则,返回的是后:n.MonDayNote

多亏了其他贡献者,我才开始着手自己的问题。


        var schedLocations = (from f in db.RAMS_REVENUE_LOCATIONS
              join n in db.RAMS_LOCATION_PLANNED_MANNING on f.revenueCenterID equals

                  n.revenueCenterID into lm

              from n in lm.DefaultIfEmpty()

              join r in db.RAMS_LOCATION_SCHED_NOTE on f.revenueCenterID equals r.revenueCenterID
              into locnotes

              from r in locnotes.DefaultIfEmpty()
              where f.LocID == nLocID && f.In_Use == true && f.revenueCenterID > 1000

              orderby f.Areano ascending, f.Locname ascending
              select new
              {
                  Facname = f.Locname,
                  f.Areano,
                  f.revenueCenterID,
                  f.Locabbrev,

                  //  MonNote = n == null ? "__" : n.MonDayNote,
                  MonNote = n == null ? "__" : n.MonDayNote,
                  TueNote = n == null ? "__" : n.TueDayNote,
                  WedNote = n == null ? "__" : n.WedDayNote,
                  ThuNote = n == null ? "__" : n.ThuDayNote,

                  FriNote = n == null ? "__" : n.FriDayNote,
                  SatNote = n == null ? "__" : n.SatDayNote,
                  SunNote = n == null ? "__" : n.SunDayNote,
                  MonEmpNbr = n == null ? 0 : n.MonEmpNbr,
                  TueEmpNbr = n == null ? 0 : n.TueEmpNbr,
                  WedEmpNbr = n == null ? 0 : n.WedEmpNbr,
                  ThuEmpNbr = n == null ? 0 : n.ThuEmpNbr,
                  FriEmpNbr = n == null ? 0 : n.FriEmpNbr,
                  SatEmpNbr = n == null ? 0 : n.SatEmpNbr,
                  SunEmpNbr = n == null ? 0 : n.SunEmpNbr,
                  SchedMondayDate = n == null ? dMon : n.MondaySchedDate,
                  LocNotes = r == null ? "Notes: N/A" : r.LocationNote

              }).ToList();
                Func<int, string> LambdaManning = (x) => { return x == 0 ? "" : "Manning:" + x.ToString(); };
        DataTable dt_ScheduleMaster = PsuedoSchedule.Tables["ScheduleMasterWithNotes"];
        var schedLocations2 = schedLocations.Where(x => x.SchedMondayDate == dMon);

0
class Program
{
    List<Employee> listOfEmp = new List<Employee>();
    List<Department> listOfDepart = new List<Department>();

    public Program()
    {
        listOfDepart = new List<Department>(){
            new Department { Id = 1, DeptName = "DEV" },
            new Department { Id = 2, DeptName = "QA" },
            new Department { Id = 3, DeptName = "BUILD" },
            new Department { Id = 4, DeptName = "SIT" }
        };


        listOfEmp = new List<Employee>(){
            new Employee { Empid = 1, Name = "Manikandan",DepartmentId=1 },
            new Employee { Empid = 2, Name = "Manoj" ,DepartmentId=1},
            new Employee { Empid = 3, Name = "Yokesh" ,DepartmentId=0},
            new Employee { Empid = 3, Name = "Purusotham",DepartmentId=0}
        };

    }
    static void Main(string[] args)
    {
        Program ob = new Program();
        ob.LeftJoin();
        Console.ReadLine();
    }

    private void LeftJoin()
    {
        listOfEmp.GroupJoin(listOfDepart.DefaultIfEmpty(), x => x.DepartmentId, y => y.Id, (x, y) => new { EmpId = x.Empid, EmpName = x.Name, Dpt = y.FirstOrDefault() != null ? y.FirstOrDefault().DeptName : null }).ToList().ForEach
            (z =>
            {
                Console.WriteLine("Empid:{0} EmpName:{1} Dept:{2}", z.EmpId, z.EmpName, z.Dpt);
            });
    }
}

class Employee
{
    public int Empid { get; set; }
    public string Name { get; set; }
    public int DepartmentId { get; set; }
}

class Department
{
    public int Id { get; set; }
    public string DeptName { get; set; }
}

输出值


0

根据我对类似问题的回答,这里:

Linq to SQL使用Lambda语法并在2列上进行了左外部联接(复合联接键)

此处获取代码,或克隆我的github存储库,然后播放!

查询:

        var petOwners =
            from person in People
            join pet in Pets
            on new
            {
                person.Id,
                person.Age,
            }
            equals new
            {
                pet.Id,
                Age = pet.Age * 2, // owner is twice age of pet
            }
            into pets
            from pet in pets.DefaultIfEmpty()
            select new PetOwner
            {
                Person = person,
                Pet = pet,
            };

Lambda:

        var petOwners = People.GroupJoin(
            Pets,
            person => new { person.Id, person.Age },
            pet => new { pet.Id, Age = pet.Age * 2 },
            (person, pet) => new
            {
                Person = person,
                Pets = pet,
            }).SelectMany(
            pet => pet.Pets.DefaultIfEmpty(),
            (people, pet) => new
            {
                people.Person,
                Pet = pet,
            });

0

概述:在此代码段中,我演示了如何按ID分组,其中Table1和Table2具有一对多关系。我对Id,Field1和Field2进行分组。如果需要进行第三次“表”查找,并且该子查询需要“左联接”关系,则该子查询很有用。我显示了一个左联接分组和一个子查询linq。结果是等效的。

class MyView
{
public integer Id {get,set};
    public String Field1  {get;set;}
public String Field2 {get;set;}
    public String SubQueryName {get;set;}                           
}

IList<MyView> list = await (from ci in _dbContext.Table1
                                               join cii in _dbContext.Table2
                                                   on ci.Id equals cii.Id

                                               where ci.Field1 == criterion
                                               group new
                                               {
                                                   ci.Id
                                               } by new { ci.Id, cii.Field1, ci.Field2}

                                           into pg
                                               select new MyView
                                               {
                                                   Id = pg.Key.Id,
                                                   Field1 = pg.Key.Field1,
                                                   Field2 = pg.Key.Field2,
                                                   SubQueryName=
                                                   (from chv in _dbContext.Table3 where chv.Id==pg.Key.Id select chv.Field1).FirstOrDefault()
                                               }).ToListAsync<MyView>();


 Compared to using a Left Join and Group new

IList<MyView> list = await (from ci in _dbContext.Table1
                                               join cii in _dbContext.Table2
                                                   on ci.Id equals cii.Id

                       join chv in _dbContext.Table3
                                                  on cii.Id equals chv.Id into lf_chv
                                                from chv in lf_chv.DefaultIfEmpty()

                                               where ci.Field1 == criterion
                                               group new
                                               {
                                                   ci.Id
                                               } by new { ci.Id, cii.Field1, ci.Field2, chv.FieldValue}

                                           into pg
                                               select new MyView
                                               {
                                                   Id = pg.Key.Id,
                                                   Field1 = pg.Key.Field1,
                                                   Field2 = pg.Key.Field2,
                                                   SubQueryName=pg.Key.FieldValue
                                               }).ToListAsync<MyView>();

-1
(from a in db.Assignments
     join b in db.Deliveryboys on a.AssignTo equals b.EmployeeId  

     //from d in eGroup.DefaultIfEmpty()
     join  c in  db.Deliveryboys on a.DeliverTo equals c.EmployeeId into eGroup2
     from e in eGroup2.DefaultIfEmpty()
     where (a.Collected == false)
     select new
     {
         OrderId = a.OrderId,
         DeliveryBoyID = a.AssignTo,
         AssignedBoyName = b.Name,
         Assigndate = a.Assigndate,
         Collected = a.Collected,
         CollectedDate = a.CollectedDate,
         CollectionBagNo = a.CollectionBagNo,
         DeliverTo = e == null ? "Null" : e.Name,
         DeliverDate = a.DeliverDate,
         DeliverBagNo = a.DeliverBagNo,
         Delivered = a.Delivered

     });

-1

LEFT OUTER JOIN的简单解决方案:

var setA = context.SetA;
var setB = context.SetB.Select(st=>st.Id).Distinct().ToList();
var leftOuter  = setA.Where(stA=> !setB.Contains(stA.Id)); 

注意事项

  • 为了提高性能,可以将SetB转换为Dictionary(如果这样做,则必须更改此代码:!setB.Contains(stA.Id))或HashSet
  • 如果涉及多个字段,则可以使用Set操作和实现以下类的类来实现:IEqualityComparer

左外部联接将返回匹配setAsetB答案。
NetMage
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.