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

时间:2015-10-28 11:29:42

标签: c# .net linq

我有这段代码:

//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,然后将其反弹回list,以及if defense。

有更优雅的方法吗?我根本不喜欢我的兰博风格:(

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

这个怎么样?我还没有编译它。我认为你并不过分担心优化迭代次数。

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