Jack Gray
Jack Gray

Reputation: 309

Substring in linq

My data is as below on which I want to run a linq query

MyTable
ID        DATA
1         1:40:567

my query is

var query = (from tab in MyTable
             where tab.DATA.Substring(0, tab.DATA.IndexOf(":")) == "1"))
             select new
             {
                tab.ID,
                tab.DATA
             }).ToList();

I get an error

InnerException {"Invalid length parameter passed to the LEFT or SUBSTRING function."} System.Exception {System.Data.SqlClient.SqlException}

I want the substring of the data column. Please help

Upvotes: 1

Views: 1854

Answers (5)

Artyom
Artyom

Reputation: 3571

This should work:

var query = (from tab in MyTable
             where tab.DATA.TrimStart(new [] {' ', '0', '\t'}).StartsWith("1")
             select new
             {
                tab.ID,
                tab.DATA
             }).ToList();

Upvotes: 1

ben
ben

Reputation: 428

Try this

var query = (from tab in MyTable
         where tab.DATA.Split(':')[0] == "1"))
         select new
         {
            tab.ID,
            tab.DATA
         }).ToList();

Upvotes: 1

D Stanley
D Stanley

Reputation: 152634

Your code will match any record that starts with 1:. If that is what you really want then you can just do:

var query = (from tab in MyTable
             where tab.DATA.StartsWith("1:")
             ...

This has the added benefit of being able to take advantage of an index on DATA if it exists.

Upvotes: 1

Mitat Koyuncu
Mitat Koyuncu

Reputation: 928

Try this:

var dataStartsWith = 1; // or another number

var query = (from tab in MyTable
         where tab.DATA.StartsWith(dataStartsWith + ":")
         select new
         {
            tab.ID,
            tab.DATA
         }).ToList();

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38638

Since you have one single char to verify, try to use the substring to get one char, for sample:

var data= (from tab in MyTable
             where tab.DATA.Substring(0, 1) == "1")
             select new
             {
                tab.ID,
                tab.DATA
             }).ToList();

Upvotes: 2

Related Questions