9

I need to get last two characters from an integer field coming through linq query.

Couldn't convert the integer field to String using Convert.ToString(),since LINQ doesn't support ToString().

any help?

int ret = db.tblProductionVolumes.Where(x => x.Month.ToLower().Equals(month.Substring(0, 3).ToLower()) &&
        month.Substring(month.Length - 2, 2).Equals(x.Year%100) &&
        x.BUId == namcID &&
        x.Type.ToLower().Trim().Equals(Constants.OS_VANNING)).Single().Volume; 
return (int?)ret
Jon P
  • 19,442
  • 8
  • 49
  • 72
prasanna kolla
  • 117
  • 1
  • 1
  • 3

3 Answers3

26

You can use the modulus operator as such:

123 % 100 = 23
444 % 100 = 44
103 % 100 = 3 (needs to be padded)

Then you can pad the number, for numbers that would start with a zero.

(myNumber % 100).ToString().PadLeft(2, '0')
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
  • I actually need to get the last two characters from a cloumn which holds year. Here is my code int ret = db.tblProductionVolumes.Where(x => x.Month.ToLower().Equals(month.Substring(0, 3).ToLower()) && month.Substring(month.Length - 2, 2).Equals(Equals(x.Year%100)) && x.BUId == namcID && x.Type.ToLower().Trim().Equals(Constants.OS_VANNING)).Single().Volume; return (int?)ret; – prasanna kolla Apr 20 '15 at 21:51
  • when I use Module to get last two characters, I am getting exception "Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types." – prasanna kolla Apr 20 '15 at 21:55
  • 2
    Maybe, the correct code could be: `(number % 100).ToString().PadLeft(2, '0'); ` – Taber Jan 11 '18 at 14:22
5

You can use integer modulo and div

Integer i = 1337
i % 10 will give 7
i / 10 will give 133
al-eax
  • 712
  • 5
  • 13
2

For LINQ here is how to convert integer to string :

Problem with converting int to string in Linq to entities

Then you can use regular expression to take out last two characters from the string.

Community
  • 1
  • 1
user_4685802
  • 155
  • 9