Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use LINQ Contains(string[]) instead of Contains(string)

I got one big question.

I got a linq query to put it simply looks like this:

from xx in table where xx.uid.ToString().Contains(string[]) select xx 

The values of the string[] array would be numbers like (1,45,20,10,etc...)

the Default for .Contains is .Contains(string).

I need it to do this instead: .Contains(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?

EDIT : The uid would also be a number. That's why it is converted to a string.

Help anyone?

like image 708
SpoiledTechie.com Avatar asked Oct 12 '08 01:10

SpoiledTechie.com


People also ask

How use contains in LINQ query?

LINQ Contains operator is used to check whether an element is available in sequence (collection) or not. Contains operator comes under Quantifier Operators category in LINQ Query Operators. Below is the syntax of Contains operator.

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .

Can you use LINQ on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.

What is contains in LINQ C#?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.


1 Answers

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.

[EDIT]

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]

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)); 
like image 81
tvanfosson Avatar answered Sep 24 '22 19:09

tvanfosson