我有一个int值数组int[] ids
。
我有一个数据表DataTable dt
我想只保留数据库列ID中的数组中的那些值
说int[] ids
包含[2,3,4,5]
dt
包含[2,3,4,3,4]
--- ids
此处可能会重复
因此输出ids
只有[2,3,4]
请用lambda或linq建议......
我用两个foreachs尝试了粗暴的方式。
答案 0 :(得分:4)
使用
int[] myIDs = (from d in dt.AsEnumerable() select d.Field<int>("id")).Intersect (ids).ToArray();
供参考,见:
答案 1 :(得分:1)
您需要创建一个新数组。 数组是固定大小的。
如果您想要一个能够删除元素的数据结构,则需要一个List。 请注意,列表删除操作的最坏情况复杂度为O(n)。
对于你的特殊问题,我会写这样的东西:
public int[] MyFunc(DataTable dt, int[] array)
{
Set<int> allowedsIds = new Set<int>();
Fill your set with ids you want to keep
int[] newArray = new int[inputArray.Length];
int newArrayCount = 0;
for (int i = 0; i < inputArray.Length; ++i)
{
if (allowedsIds.Contains(inputArray[i]))
{
newArray[newArrayCount++] = inputArray[i];
}
}
Array.Resize(ref newArray, newArrayCount);
return newArray;
}
答案 2 :(得分:0)
使用相交功能:
var ids = new[] {2, 3, 4, 5};
var dt = new[] {2, 3, 4, 3, 4};
foreach (var id in ids.Intersect(dt))
{
}
答案 3 :(得分:0)
您可以创建List<int> fromDB
和(在数据集上循环)用ids列值填充它
然后你可以使用:
List<int> result = ids.Intersect(fromDB).ToList();
答案 4 :(得分:0)
您需要两个集合的交集。 Linq作为Intersect方法。
来自Linq 101样本:
public void Linq50()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var commonNumbers = numbersA.Intersect(numbersB);
Console.WriteLine("Common numbers shared by both arrays:");
foreach (var n in commonNumbers)
{
Console.WriteLine(n);
}
}
您可以在Linq 101 Samples中找到更多示例。