user3403034
user3403034

Reputation: 1

How to do string combining and querying with Linq

How can I combine variables to a string and use the string in a where condition within a LINQ query? I have tried this:

query = query.Where(p => (p.Cod + p.Year + p.Count).StartsWith("BS201412"));

My variables are as follows:

I have also tried this:

  query = query.Where(p => (p.Cod + SqlFunctions.StringConvert((double) p.Year)+ SqlFunctions.StringConvert((double) p.Count)).StartsWith("BS201412"));

but because of Year the query is not working in both variants.

Upvotes: 0

Views: 193

Answers (1)

keenthinker
keenthinker

Reputation: 7820

You have many options and two of them are:

  1. use String.Format - it converts automatically every parameter to string
  2. use the ToString method on the complex variable

Example:

string cod = "BS";
short year = 14;
int count = 100;
Console.WriteLine(String.Format("{0}{1}{2}", cod, year, count));
Console.WriteLine(cod + year.ToString() + count.ToString());

The output is in both cases the same:

BS14100
BS14100

Your query line could look like this:

query = query
        .Where(p => String.Format("{0}{1}{2}", p.Cod, p.Year, p.Count)
        .StartsWith("BS201412"));

Because you are using LINQ2SQL some of the functions can not be used (because they can not be translated to SQL directly). You can try a different approach - it looks like you have the String you want to search for BS201420, so you can partition the string, convert every part to the corresponding type and write a normal query, something like this:

var searchFor = "BS201420";
var cod = searchFor.Substring(0, 2);
// example - use short.TryParse in your code
var year = short.Parse(searchFor.Substring(2, 4));
// example - use int.TryParse in your code
var count = int.Parse(searchFor.Substring(4,2));
query = query.Where(p => p.Cod == cod && p.Year == year && p.Count == count);

This should find the same result set as with the string and starts with.

Upvotes: 2

Related Questions