如何使用 LINQ Contains(string[]) 而不是 Contains(string) [英] How do I use LINQ Contains(string[]) instead of Contains(string)
问题描述
我有一个大问题.
我有一个 linq 查询,它看起来像这样:
I got a linq query to put it simply looks like this:
from xx in table
where xx.uid.ToString().Contains(string[])
select xx
string[]
数组的值将是类似 (1,45,20,10,etc...) 的数字
The values of the string[]
array would be numbers like (1,45,20,10,etc...)
.Contains
的默认值是 .Contains(string)
.
我需要它来代替:.Contains(string[])
...
I need it to do this instead: .Contains(string[])
...
一位用户建议为 string[]
编写一个扩展类.我想学习如何学习,但有人愿意为我指明正确的方向吗?
EDIT : One user suggested writing an extension class for string[]
. I would like to learn how, but any one willing to point me in the right direction?
uid 也将是一个数字.这就是它被转换为字符串的原因.
EDIT : The uid would also be a number. That's why it is converted to a string.
帮助任何人?
推荐答案
spoulson 几乎正确,但您需要从 string[]
Listint
,则 List
会更好.List
支持 Contains()
.执行 uid.ToString().Contains(string[])
将意味着 uid 作为字符串包含数组的所有值作为子字符串???即使您确实编写了扩展方法,它的意义也是错误的.
spoulson has it nearly right, but you need to create a List<string>
from string[]
first. Actually a List<int>
would be better if uid is also int
. List<T>
supports Contains()
. Doing uid.ToString().Contains(string[])
would imply that the uid as a string contains all of the values of the array as a substring??? Even if you did write the extension method the sense of it would be wrong.
除非您像 Mitch Wheat 演示的那样更改它并为 string[]
编写它,否则您只能跳过转换步骤.
Unless you changed it around and wrote it for string[]
as Mitch Wheat demonstrates, then you'd just be able to skip the conversion step.
[结束]
这就是您想要的,如果您不使用扩展方法(除非您已经将潜在的 uid 集合作为整数 - 则只需使用 List
代替).这使用了链式方法语法,我认为它更简洁,并且转换为 int 以确保查询可用于更多提供程序.
Here is what you want, if you don't do the extension method (unless you already have the collection of potential uids as ints -- then just use List<int>()
instead). This uses the chained method syntax, which I think is cleaner, and
does the conversion to int to ensure that the query can be used with more providers.
var uids = arrayofuids.Select(id => int.Parse(id)).ToList();
var selected = table.Where(t => uids.Contains(t.uid));
这篇关于如何使用 LINQ Contains(string[]) 而不是 Contains(string)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!