How to write Linq left join with multiple fields where one is case insensitive

旧时模样 提交于 2019-12-12 04:37:49

问题


What is preferred way to convert this to a Left Join? This is Linq to Objects (not 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();

Issues: Tradeoff between readability vs. efficiency. Should try to avoid ToLowerInvariant()?


回答1:


For left joins you need to use 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();



回答2:


what you write is cross join, not 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();


来源:https://stackoverflow.com/questions/25254939/how-to-write-linq-left-join-with-multiple-fields-where-one-is-case-insensitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!