3

in one of my database fields i have data as follows:

value1, value2, value3

my search parameter could be value1 or value2 or value3

what i want to do is use a linq query to get a list of entities where for e.g. value2 is in "value1, value2, value3"

also, values are seperated by space after the commma.

i tried to use the following linq query but got an error that stated Array operation not permitted.

List<Players> c = (from p in db.Players
                      where (p.Users == "Everyone" || p.Users.Split()[','].Trim().Contains(username))
                      orderby p.Category ascending
                      select p).ToList();

any ideas how this can be accomplished?

Habib
  • 219,104
  • 29
  • 407
  • 436
user1144596
  • 2,068
  • 8
  • 36
  • 56

2 Answers2

7

You are not doing the Split properly, it should be like:

p.Users.Split(',').Contains(username)

If you want to Trim each split value then:

p.Users.Split(',').Select(r=> r.Trim).Contains(username)

If you are using LINQ to Entities, then you might end up with an exception that string.Split can't be translated in to SQL query. In that case you might have to iterate (ToList) your results first and then compare it against the split array.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • This is no longer working in ASP.NETCore it will throw 'An expression tree may not contain a call or invocation that uses optional arguments' – Rahul Uttarkar Jul 31 '20 at 07:54
0

Fist of all it is not a good practice to use a datamodel where you need string split match. Because it leads to inefficient systems and not to mention slow queries. But yet, if you really need a solution why not try this -.

There are four occasions where you will get a match,

  1. A prefix match - starting with
  2. Inner Match - contains with
  3. Suffix Match - ends with
  4. The only match - only one item and this is it

considering the scenario I am suggesting the solution below -

username is the value looking for say "1"
string prefixMatch = username + ",";
string suffixMatch = ", " + username;
string innerMatch = ", " + username + ",";

List<Players> c = (from p in db.Players
                  where (p.Users == "Everyone" || (p.StartsWith(prefixMatch) ||
                                                   p.Contains(innerMatch) || p.EndsWith(suffixMatch) || 
                                                   (!p.Contains(",") && p == username)))
                  orderby p.Category ascending
                  select p).ToList();

This query will support LINQ-TO-SQL Conversion

brainless coder
  • 6,310
  • 1
  • 20
  • 36