Reputation: 364
I have a comma separated string stored in database.
E.g.: record1 = "1,3,5,7,9,10"
and record2 = "4,5,10"
And I have a given information, E.g.: 1
.
I have to select the record using LINQ that contains the given info of 1.
The result returned should be record1.
If I were to use .contains() solely, it's not accurate as record2 will be returned as well.
How can I achieve that? Is it possible to achieve that in a single LINQ query?
Thanks for advise !
Upvotes: 1
Views: 3677
Reputation: 6430
First of all I would like to mention what @Tim Schmelter said -
Have you noticed already that the real problem is your creepy datamodel? Use a table with real records instead of a column with a comma separated string.
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,
considering the scenario I am suggesting the solution below -
s is the value looking for say "1"
string prefixMatch = s + ",";
string suffixMatch = "," + s;
string innerMatch = "," + s + ",";
string record = <dbRecords>.FirstOrDefault(r=> r.StartsWith(prefixMatch) ||
r.Contains(innerMatch) || r.EndsWith(suffixMatch) ||
(!r.Contains(",") && r == s));
The reason for such a detailed query is to keep your memory utilisation less and letting the SQL query do the hard work of finding the results because this query will support LINQ-to-SQL conversion.
Upvotes: 1
Reputation: 1036
Instead of searching 1 you can try 1,(1 and comma combined) for searching in Contains in linQ
Upvotes: 0
Reputation: 1432
If i understand you correctly, you need as result record that contains "1". So you can use:
private bool GerRecord(string record)
{
string[] arr=record.Split(',');
return arr.Contains("1");
}
Upvotes: 0
Reputation: 78525
With a single LINQ-to-objects query:
string[] records = new[] { record1, record2 };
string record = records.FirstOrDefault(r => r.Split(',').Any(s => s == "1"));
Upvotes: 6