如何使用多个字段编写Linq左连接,其中一个不区分大小写

时间:2014-08-12 01:44:21

标签: c# linq left-join linq-to-objects

将此转换为左连接的首选方法是什么?这是Linq to Objects(不是SQL)。

var result = 
(
   from e in entries
   from r in results
   where r.PropertyId == e.PropertyId &&
         e.ValueAsString.Equals(r.Value, StringComparison.InvariantCultureIgnoreCase)
   select new
   {
      Result = r,
      Entry = e
  }
)
.ToList();

问题:可读性与效率之间的权衡。应该尽量避免ToLowerInvariant()?

2 个答案:

答案 0 :(得分:0)

你写的是cross join,而不是left join

var result = 
(
   from e in entries
   join r in results
   let ev=e.ValueAsString.ToLower()
   let rv=r.Value.ToLower()
   on new{e.PropertyId,ev} equals new {r.PropertyId,rv } into lg
   from r in lg.DefaultIfEmpty()
   select new
   {
      Result = r,
      Entry = e
  }
)
.ToList();

答案 1 :(得分:0)

对于左连接,您需要使用DefaultIfEmpty

var result = 
    (
       from e in entries
       from r in results.Where(x => x.PropertyId == e.PropertyId)
                        .Where(x => e.ValueAsString.Equals(x.Value, StringComparison.InvariantCultureIgnoreCase))
                        .DefaultIfEmpty()
       select new
       {
          Result = r,
          Entry = e
      }
    )
    .ToList();