简体   繁体   中英

What is LINQ equivalent of SQL

List<string> li = new List<string>();
        li.Add("10,11,12,1");
        li.Add("10,11,12,13");

        var q = from d in li
                where d.Contains("1")
                select d;

I have a list of string with two values. I have single value "1" and I want to fetch that list object which contains value "1" in string ie I want first object in list. If I use contains then it will return both list object values, so what will be query which gives me the perfect result?

Try changing the where to

where d.Split(',').Contains("1")

This will split the string into a list of items, and then check if the item is in that list.

EDIT:

As mentioned in the comments, you do not need the ToList() so changethe above.

If you want to run this query directly against database, you'll have to do something like this:

 var q = from d in li
            where d.StartsWith("1,") || d.EndsWith(",1") || d.Contains(",1,") 
             || d.Equals("1")
            select d;

Otherwise the other answer works in memory

You can try this:

List<string> li = new List<string>();
li.Add("10,11,12,1");
li.Add("10,11,12,13");
string searchItem = "1";
var q = from d in li
        where ("," + d + ",").Contains("," + searchItem + ",")
        select d;

and this query will also work for directly against database.

Try this:

var q =
    from d in li
    where d.Split(',').Any(x => x == "1")
    select d;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM