【发布时间】: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 可能正在删除项目。