【问题标题】:Better way of assigning the variable during LINQ Query在 LINQ 查询期间分配变量的更好方法
【发布时间】:2015-10-28 21:34:33
【问题描述】:

我有这段代码:

//This is coming from an Excell sheet
var ListOfPropertyElements = dataInternal
           .Select(element => new
           {
               PersonName = DC.EncryptToString((string)element.PersonName),
               KeyDate = (DateTime)element.KeyDate
           })
           .Distinct().ToList();


 List<int> idList = new List<int>();//This is used to delete records

 //trying to check do I have records in SQL with the ListOfPropertyElements     
 foreach (var listitems in ListOfPropertyElements)
 {
     var temp = dbContext.tbl_person
       .Where(item => item.ItemName == listitems.personName &&                  
                      item.KeyDate == listitems.KeyDate)
       .Select(item => item.personID)
       .ToArray();

       if (temp.Length > 0)
       {
           idList.Add(temp[0]);
       }
 }

作为最终结果,我得到了一个整数列表。填充 idList 变量的方式让我感到困扰。在 LINQ 执行期间,我将结果转换为数组,然后将其反弹回列表,以及 if 防御。

有没有更优雅的方法来做到这一点?我一点也不喜欢我的 Rambo 风格 :(

【问题讨论】:

  • 只需删除ToArray(),添加Take(1) 并致电idList.AddRange(temp)。我相信您也可以简化foeach()。你试过什么?
  • 我刚刚更新了我的问题
  • 而不是ToArray(),您是否只需要FirstOrDefault(),因为您只向idList 添加单个项目?
  • 您对数据源生成 N 个查询。如果您的ListOfPropertyElements 不是太大,您可以尝试生成更优化的查询。
  • @YeldarKurmangaliyev 匿名类会覆盖Equals,这样如果所有属性都相等,它们就相等。所以 Distinct 可能正在删除项目。

标签: c# .net linq


【解决方案1】:

可以直接填充idList:-

List<int> idList =  dbContext.tbl_person
                    .Where(item => ListOfPropertyElements.Select(x => x.PersonName)
                                                         .Contains(item.PersonName) 
                                && ListOfPropertyElements.Select(x => x.KeyDate)
                                                         .Contains(item.KeyDate)))
                    .Select(item => item.personID).ToList();

【讨论】:

  • listitem 是 foreach 循环中 ListOfPropertyElements 的成员。这怎么行?
  • 返回这个错误:Local Sequences can not be used in LINQ to SQL implementation of query operator 。例外:包含运算符。
  • 如果我使用包含,则会报错,无法将 lambda 表达式类型转换为“匿名类型”
  • (参数)? x 错误:无法将 Lambda 表达式转换为类型“匿名类型#1”,因为它不是委托类型。
  • @Rahin Singh。非常感谢您在解决此问题的同时花时间在聊天上!!!。
【解决方案2】:

这个怎么样?我没有编译它。而且我假设您并不过分关注优化迭代次数。

//Excel sheet data
var ListOfPropertyElements = dataInternal.Select(element => new { PersonName = DC.EncryptToString((string)element.PersonName),
                                                                  KeyDate = (DateTime)element.KeyDate }).Distinct();

//Filtered Id's
var idList = dbContext.tbl_person.Where(item => ListOfPropertyElements.Any(pElement => item.ItemName == pElement.PersonName && item.KeyDate == pElement.KeyDate))
                                 .Select(fItem => fItem.personID).ToList(); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2012-05-16
    相关资源
    最近更新 更多