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

2019-01-02 18:07发布

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?

20条回答
闭嘴吧你
2楼-- · 2019-01-02 18:23

You should write it the other way around, checking your priviliged user id list contains the id on that row of table:

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

LINQ behaves quite bright here and converts it to 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 basicly embeds the contents of the 'search' array into the sql query, and does the filtering with 'IN' keyword in SQL.

查看更多
明月照影归
3楼-- · 2019-01-02 18:24

Try:

var stringInput = "test";
var listOfNames = GetNames();
var result = from names in listOfNames where names.firstName.Trim().ToLower().Contains(stringInput.Trim().ToLower());
select names;
查看更多
旧人旧事旧时光
4楼-- · 2019-01-02 18:25

I believe you could also do something like this.

from xx in table
where (from yy in string[] 
       select yy).Contains(xx.uid.ToString())
select xx
查看更多
倾城一夜雪
5楼-- · 2019-01-02 18:27

This is an example of one way of writing an extension method (note: I wouldn't use this for very large arrays; another data structure would be more appropriate...):

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;
        }
    }
}
查看更多
路过你的时光
6楼-- · 2019-01-02 18:28

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

string[] values = new[] { "1", "2", "3" };
string data = "some string 1";
bool containsAny = values.Any(data.Contains);
查看更多
冷夜・残月
7楼-- · 2019-01-02 18:31

Or if you already have the data in a list and prefer the other 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();
查看更多
登录 后发表回答