我如何使用LINQ包含(字符串[]),而不是包含(字符串) [英] 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
在字符串值[]
阵列会像数字(1,45,20,10,等...)
The values of the string[]
array would be numbers like (1,45,20,10,etc...)
为。载
默认为。载有(串)
。
我需要做的这个代替:。载有(串[])
...
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 []
第一。其实一个列表与LT; INT>
会更好,如果uid是也 INT
。 列表< T>
支持包含()
。做 uid.ToString()。包含(字符串[])
将意味着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.
除非你周围变化并把它写在的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.
[EndEdit中]
下面是你想要什么,如果你不这样做的扩展方法(除非你已经有潜在的UID的集合作为整数 - 那么就使用列表&LT; INT&GT;()
代替)。本品采用链式方法的语法,我认为这是更清洁和
并转换为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包含(字符串[]),而不是包含(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!