How to use LINQ Contains (string []) instead of Contains (string)

I have one big question.

I got a linq request so it looks like this:

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

The values ​​of the string[] array will be numbers such as (1,45,20,10, etc.)

The default value for .Contains is .Contains(string) .

I need to do this instead: .Contains(string[]) ...

EDIT: One user suggested writing an extension class for string[] . I would like to know how, but someone wants to point me in the right direction?

EDIT:. uid will also be a number. That is why it is converted to a string.

Help someone?

+81
string contains c # linq
Oct 12 '08 at 1:14
source share
20 answers

spoulson is almost right, but first you need to create a List<string> from string[] . Actually a List<int> would be better if uid is also int . List<T> supports Contains() . Executing uid.ToString().Contains(string[]) means that uid as a string contains all array values ​​as a substring ??? Even if you wrote an extension method, the meaning of this would be wrong.

[EDIT]

If you did not change it and write to string[] , as Mitch Wheat demonstrates, you can simply skip the conversion step.

[ENDEDIT]

Here is what you want if you don't use the extension method (if you don't already have a collection of potential uids as ints) then just use List<int>() ). In this case, chaining syntax is used, which, in my opinion, is cleaner and does a conversion to int to ensure that the request can be used with a large number of providers.

 var uids = arrayofuids.Select(id => int.Parse(id)).ToList(); var selected = table.Where(t => uids.Contains(t.uid)); 
+66
Oct 12 '08 at 2:01
source share

If you really want to replicate Contains, but for an array, this is an extension method and sample code to use:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ContainsAnyThingy { class Program { static void Main(string[] args) { string testValue = "123345789"; //will print true Console.WriteLine(testValue.ContainsAny("123", "987", "554")); //but so will this also print true Console.WriteLine(testValue.ContainsAny("1", "987", "554")); Console.ReadKey(); } } public static class StringExtensions { public static bool ContainsAny(this string str, params string[] values) { if (!string.IsNullOrEmpty(str) || values.Length > 0) { foreach (string value in values) { if(str.Contains(value)) return true; } } return false; } } } 
+31
Oct 12 '08 at 16:00
source share

Try the following.

 string input = "someString"; string[] toSearchFor = GetSearchStrings(); var containsAll = toSearchFor.All(x => input.Contains(x)); 
+16
Oct 12 '08 at 2:03
source share

LINQ in .NET 4.0 has another option for you; .Any () method;

 string[] values = new[] { "1", "2", "3" }; string data = "some string 1"; bool containsAny = values.Any(data.Contains); 
+13
Mar 14 '12 at 22:40
source share

Or, if you already have data in the list and prefer a different Linq format :)

 List<string> uids = new List<string>(){"1", "45", "20", "10"}; List<user> table = GetDataFromSomewhere(); List<user> newTable = table.Where(xx => uids.Contains(xx.uid)).ToList(); 
+5
Apr 28 2018-11-11T00:
source share

What about:

 from xx in table where stringarray.Contains(xx.uid.ToString()) select xx 
+3
Oct 12 '08 at 1:24
source share

This is an example of one way of writing an extension method (note: I would not use it for very large arrays, and another data structure would be more suitable ...):

 namespace StringExtensionMethods { public static class StringExtension { public static bool Contains(this string[] stringarray, string pat) { bool result = false; foreach (string s in stringarray) { if (s == pat) { result = true; break; } } return result; } } } 
+2
Oct 12 '08 at 1:54
source share

This is a late answer, but I find it still useful. I created the NinjaNye.SearchExtension nuget package that can help solve this problem .:

 string[] terms = new[]{"search", "term", "collection"}; var result = context.Table.Search(terms, x => x.Name); 

You can also search for multiple row properties

 var result = context.Table.Search(terms, x => x.Name, p.Description); 

Or do a RankedSearch , which returns an IQueryable<IRanked<T>> , which simply includes a property that shows how many times search queries have appeared:

 //Perform search and rank results by the most hits var result = context.Table.RankedSearch(terms, x => x.Name, x.Description) .OrderByDescending(r = r.Hits); 

There is a more detailed project guide for the GitHub page: https://github.com/ninjanye/SearchExtensions

Hope this helps future visitors.

+2
Feb 13 '14 at 9:07
source share

I believe that you can also do something like this.

 from xx in table where (from yy in string[] select yy).Contains(xx.uid.ToString()) select xx 
+1
Oct 12 '08 at 1:59
source share

Linq extension method. Will work with any IEnumerable object:

  public static bool ContainsAny<T>(this IEnumerable<T> Collection, IEnumerable<T> Values) { return Collection.Any(x=> Values.Contains(x)); } 

Using:

 string[] Array1 = {"1", "2"}; string[] Array2 = {"2", "4"}; bool Array2ItemsInArray1 = List1.ContainsAny(List2); 
+1
Apr 17 '14 at 3:55
source share

Did I understand correctly that uid is a unique identifier (Guid)? Is this just an example of a possible scenario, or are you really trying to find a guide that matches an array of strings?

If this is true, you can really rethink this whole approach, it seems like a very bad idea. You should probably try matching the Guide to Guide.

 Guid id = new Guid(uid); var query = from xx in table where xx.uid == id select xx; 

I honestly can't imagine a scenario where combining an array of strings using "contains" to the Guid content would be a good idea. Firstly, Contains () does not guarantee the order of numbers in Guid, so that you can match multiple elements. Not to mention that comparing guides in this way would be slower than just doing it directly.

0
Oct 12 '08 at 16:38
source share

You should write this differently, verifying that your preferred list of user identifiers contains an identifier in this row of the table:

 string[] search = new string[] { "2", "3" }; var result = from x in xx where search.Contains(x.uid.ToString()) select x; 

LINQ behaves quite brightly and converts it into a good SQL statement:

 sp_executesql N'SELECT [t0].[uid] FROM [dbo].[xx] AS [t0] WHERE (CONVERT(NVarChar,[t0].[uid])) IN (@p0, @p1)',N'@p0 nvarchar(1), @p1 nvarchar(1)',@p0=N'2',@p1=N'3' 

which basically embeds the contents of the β€œsearch” array in the sql query and performs filtering with the keyword β€œIN” in SQL.

0
Jan 19 '09 at 5:17
source share

I managed to find a solution, but not very good, because for this I need to use AsEnumerable (), which will return all the results from the database, fortunately I only have 1k records in the table, so this is not very noticeable, but it goes here.

 var users = from u in (from u in ctx.Users where u.Mod_Status != "D" select u).AsEnumerable() where ar.All(n => u.FullName.IndexOf(n, StringComparison.InvariantCultureIgnoreCase) >= 0) select u; 



My original post:

How do you do the opposite? I want to do something like the following in essence.

 string[] search = new string[] { "John", "Doe" }; var users = from u in ctx.Users from s in search where u.FullName.Contains(s) select u; 

I want to find all users where their FullName contains all the elements in the "search". I tried a number of different ways, all of which did not work for me.

I also tried

 var users = from u in ctx.Users select u; foreach (string s in search) { users = users.Where(u => u.FullName.Contains(s)); } 

In this version, only those are found that contain the last element in the search array.

0
Jul 17 '09 at 9:21
source share

The best solution I found was to continue working on a table function in SQL that produces results like:

 CREATE function [dbo].[getMatches](@textStr nvarchar(50)) returns @MatchTbl table( Fullname nvarchar(50) null, ID nvarchar(50) null ) as begin declare @SearchStr nvarchar(50); set @SearchStr = '%' + @textStr + '%'; insert into @MatchTbl select (LName + ', ' + FName + ' ' + MName) AS FullName, ID = ID from employees where LName like @SearchStr; return; end GO select * from dbo.getMatches('j') 

Then you simply drag and drop the function into your LINQ.dbml designer and name it the same as other objects. LINQ even knows the columns of your stored function. I call it the following:

 Dim db As New NobleLINQ Dim LNameSearch As String = txt_searchLName.Text Dim hlink As HyperLink For Each ee In db.getMatches(LNameSearch) hlink = New HyperLink With {.Text = ee.Fullname & "<br />", .NavigateUrl = "?ID=" & ee.ID} pnl_results.Controls.Add(hlink) Next 

Incredibly simple and really applying the power of SQL and LINQ in the application ... and you, of course, can generate any function that you need for the same effects!

0
Jun 18 2018-10-18
source share

I believe that you really want to: suppose the scenario you have two databases and they have a table of common products And you want to select products from table "A" that have a common identifier with "B"

using this method, it will be too difficult to do this what we do is intersection, and there is a method called intersection for this

example from msdn: http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#intersect1

int [] numbers = (0, 2, 4, 5, 6, 8, 9); int [] numbersB = (1, 3, 5, 7, 8); var = commonNumbers numbersA.Intersect (numbersB);

I think you need to easily solve using intersection

0
Aug 04 '10 at 3:22
source share
 from xx in table where xx.uid.Split(',').Contains(string value ) select xx 
0
Jul 30 '12 at 7:02
source share

Check out this extension method:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ContainsAnyProgram { class Program { static void Main(string[] args) { const string iphoneAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like..."; var majorAgents = new[] { "iPhone", "Android", "iPad" }; var minorAgents = new[] { "Blackberry", "Windows Phone" }; // true Console.WriteLine(iphoneAgent.ContainsAny(majorAgents)); // false Console.WriteLine(iphoneAgent.ContainsAny(minorAgents)); Console.ReadKey(); } } public static class StringExtensions { /// <summary> /// Replicates Contains but for an array /// </summary> /// <param name="str">The string.</param> /// <param name="values">The values.</param> /// <returns></returns> public static bool ContainsAny(this string str, params string[] values) { if (!string.IsNullOrEmpty(str) && values.Length > 0) return values.Any(str.Contains); return false; } } } 
0
Aug 10 2018-12-12T00:
source share

Try:

 var stringInput = "test"; var listOfNames = GetNames(); var result = from names in listOfNames where names.firstName.Trim().ToLower().Contains(stringInput.Trim().ToLower()); select names; 
0
Aug 08 '15 at 13:17
source share
 string[] stringArray = {1,45,20,10}; from xx in table where stringArray.Contains(xx.uid.ToString()) select xx 
-one
Aug 31 '10 at 17:48
source share
 Dim stringArray() = {"Pink Floyd", "AC/DC"} Dim inSQL = From alb In albums Where stringArray.Contains(alb.Field(Of String)("Artiste").ToString()) Select New With { .Album = alb.Field(Of String)("Album"), .Annee = StrReverse(alb.Field(Of Integer)("Annee").ToString()) } 
-2
Oct. 16 '16 at 18:21
source share



All Articles