Reputation: 2521
I have a Db table with a csv field called "Line". There are several values in the field separated by semicolons.
I am trying to find a LINQ expression to check if there is any row where the second value in the "Line" field has a specific value.
Something like:
if (dbContext.Test.Any(t => Array.IndexOf(t.Line.Split(';'), value) = 1))
{
Do something ...
}
Example:
Line = "value1;apple;value3;value4"
if (dbContext.Test.Any("second value in Line field equals 'apple'"))
{
Do something ...
}
What's the most straight-forward and concise way to do this?
Upvotes: 3
Views: 360
Reputation: 152626
Since you appear to be using a DbContext
and there's no mechanism to translate splitting a string or searching by index you'll need to get more data than necessary, then filter in linq-to-objects. You could to an initial basic filter to limit the number of rows coming back, but you'll need to do the remaining filtering in-memory:
var queryEF = dbContext.Test
.Where(t => t.Line.Contains(";" + value" + ";");
var queryMemory = queryEF.AsEnumerable() // shift to Linq-to-Objects
.Where((t => Array.IndexOf(t.Line.Split(';'), value) == 1);
if (queryMemory.Any())
{
//Do something ...
}
Upvotes: 1
Reputation: 2742
So as I understand it, your table (dbContext) contains a collection of rows (Test)?
You can use 'where' to reduce that collection down to only elements that meet the condition (in this case, I split the string by the semi-colon and see if the second string is equal to apple. 'Any' will then return true if there were one or more matches.
if(dbContext.Test.Where(x => x.Line.Split(';')[1] == "apple").Any())
{
// Do the thing
}
Upvotes: 0
Reputation: 21108
If you just want to check the value Linq is a simple method for this.
Just do the following:
You should consider to normalize your data, because of storing redundant/unnormalized data could cause other problems.
EDIT
Ok, working with linq in this case is not as easy as i thought, because we do not have any index information. This is easy and should work:
string line = "value1;apple;value3;value4";
string[] splitted = line.Split(new char[] { ';' });
if (splitted.Length > 1 && splitted[1] == "apple")
{
Console.WriteLine("APPLE!");
}
Upvotes: 0