简体   繁体   English

如何在LINQ函数中以元素方式比较数组

[英]How to element-wise compare arrays in LINQ functions

My issue is the following: 我的问题如下:

Dim dt As DataTable = GetSomeDataTable()
Dim exceptions As List(Of String())({{"a","b"},{"c","d"}})
For Each j As Integer In Enumerable.Range(0, dt.Rows.Count) _
                                   .Where(Function(j1) exceptions.Contains({CStr(dt.Rows(j1)(0)), CStr(dt.Rows(j1)(1)}))
    ' Do something
Next

In the above, the code in the loop never executes even if there are rows in dt with first element "a", second element "b" for example, because the IEnumerable.Contains method doesn't match one array {"a", "b"} with another array {"a", "b"}. 在上面,循环中的代码永远不会执行,即使dt中有第一个元素“a”,第二个元素“b”,例如,因为IEnumerable.Contains方法与一个数组{“a”不匹配, “b”}与另一个数组{“a”,“b”}。 I'm guessing the comparison is done by reference rather than by value? 我猜测比较是通过引用而不是通过值来完成的? What I want is for the Contains method to consider two arrays A and B equal iff A(i) = B(i) for all i = 0, 1, ... . 我想要的是Contains方法考虑两个数组A和B等于iff A(i)= B(i)所有i = 0,1,.... I've noticed this behavior with the IEnumerable.Distinct() as well and managed to overcome it by making a custom EqualityComparer, but I felt this was quite cumbersome. 我已经注意到IEnumerable.Distinct()的这种行为并设法通过制作自定义EqualityComparer来克服它,但我觉得这非常麻烦。 Does anyone know a slicker way to achieve this? 有谁知道一个更光滑的方式来实现这一目标? Or just a general way to compare multiple-element primary keys in .Net? 或者只是比较.Net中多元素主键的一般方法? (Concatenating the strings with an illegal character doesn't count.) (用非法字符连接字符串不算数。)

Your problem is that you try to compare arrays. 您的问题是您尝试比较数组。 You're right that the comparison is done by reference rather than by value. 你是对的,比较是通过引用而不是通过值来完成的。 Either use another type like Tuple , or use Join (which is also probably faster than the Where / Contains combo): 要么使用像Tuple这样的其他类型,要么使用Join (也可能比Where / Contains组合更快):

Dim rows = from row in dt.AsEnumerable()                     
           join e in exceptions on row(0) Equals e(0) And row(1) Equals e(1)

For Each row in rows
    ' do something '
Next

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM