C# 如何检查<;T1>;包含<;T2>;如果T2是T1属性之一?
我有一个本地ID列表,我需要检查C# 如何检查<;T1>;包含<;T2>;如果T2是T1属性之一?,c#,entity-framework,collections,C#,Entity Framework,Collections,我有一个本地ID列表,我需要检查DB.Table中是否存在此ID 我编写了以下代码: List<int> localIdList; //filling localIdList var idArrayFromDb = DB.Table .Select(s => s.ID) .ToArray(); bool isSubset = !localIdList .Excep
DB.Table
中是否存在此ID
我编写了以下代码:
List<int> localIdList;
//filling localIdList
var idArrayFromDb = DB.Table
.Select(s => s.ID)
.ToArray();
bool isSubset = !localIdList
.Except(idListFromDb)
.Any();
列表本地化列表;
//填写本地化列表
var idArrayFromDb=DB.Table
.选择(s=>s.ID)
.ToArray();
bool isSubset=!地方名单
.除了(idListFromDb)
.Any();
目前它运行良好,但我认为这不是解决这个问题的最佳方法
所以我想知道,我是否可以在不从DB收集ID集合或其他更好的方法的情况下也这样做?试试这个
//sample
List<int> t1 = new List<int>();
t1.Add(1);
t1.Add(2);
t1.Add(3);
List<int> t2 = new List<int>();
t2.Add(2);
bool res = t2.Any(a => t1.Any(b => b == a));
Console.WriteLine("res :" + res);
// your solution here
bool isSubset = DB.Table.Any(s => localIdList.any(l=> l == s.ID));
//示例
列表t1=新列表();
t1.加入(1);
t1.加入(2);
t1.加入(3);
列表t2=新列表();
t2.加入(2);
bool res=t2.Any(a=>t1.Any(b=>b==a));
控制台写入线(“res:+res”);
//你的解决方案在这里
bool isSubset=DB.Table.Any(s=>localIdList.Any(l=>l==s.ID));
一种方法是使用列表法
@CodeCaster 1提到的一个问题是,它将受到localIdList长度的限制 这是否有效取决于ID列表的大小。SQL Server对在in()子句中可以使用多少值有限制。另外,“Try”不是一个答案,请解释您的代码在做什么。
bool isSubset = DB.Table.Where(s => localIdList.Contains(s)).Any();