在LINQ查询期间分配变量的更好方法

本文关键字:变量 更好 方法 分配 LINQ 查询 | 更新日期: 2023-09-27 18:19:39

我有一段代码:

//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执行过程中,我将结果转换为Array,然后将其与if防御一起反弹到列表中。

有更优雅的方法吗?我一点也不喜欢我的兰博风格:(

在LINQ查询期间分配变量的更好方法

您可以直接填充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();

这个怎么样?我还没有编译它。我想你不会过度关注优化迭代次数。

//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();