2009-08-04 186 views
48

如何將字符串轉換爲int?無下面做的作品:Linq int字符串

from s in ctx.Services 
    where s.Code.ToString().StartsWith("1") 
    select s 

from s in ctx.Services 
    where Convert.ToString(s.Code).StartsWith("1") 
    select s 

from s in ctx.Services 
    where ((string)s.Code).ToString().StartsWith("1") 
    select s 

編輯

我得到的錯誤是:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

+0

前兩個應該工作......你能詳細說明「以下哪一項......沒有工作」的含義? – 2009-08-04 15:54:56

+0

你只是沒有得到任何結果嗎?您是否確認「代碼」列包含以「1」開頭的值? – Keith 2009-08-04 15:55:49

+1

www.linqpad.net非常適合學習Linq(以及.NET中的其他任何東西)。它是免費的,強烈推薦。另外,其19美元的Intellisense非常棒。 – 2009-08-04 16:01:00

回答

-1

這裏是一個辦法做到這一點。

int[] x = new int[] {11,3,15,7,19}; 

var j = from s in x where s.ToString().StartsWith("1") select s.ToString(); 

Console.WriteLine(j); 
+7

這不會幫助他 - 他正在使用linq來實體 – ShuggyCoUk 2009-08-04 16:26:27

2

我有一個類似的問題

 IQueryable<Street> query = db.Streets.AsQueryable(); 
     query = query.Where(street => street.Name.ToLower().StartsWith(keyword)) 
         .Take(10) 
         .OrderBy(street => street.Name); 

     var list = query.Select(street => new 
     { 
      street.StreetId, 
      Name = street.Name + " " + street.Suburb.Name + " " + street.Suburb.State.Name + " " + street.Suburb.Postcode 

     }); 

street.Suburb.Postcode被拋出'不能轉換非主要類型錯誤'作爲它的int?在遵循shuggy的鏈接之後,我通過添加.AsEnumerable來強制int? - >字符串轉換'客戶端',即LINQ到對象。即

var list = query.AsEnumerable().Select(street => new 
     { 
      street.StreetId, 
      Name = street.Name + " " + street.Suburb.Name + " " + street.Suburb.State.Name + " " + street.Suburb.Postcode 

     }); 
+0

謝謝,你明確保存了我的一天。 在這裏添加`AsEnumerable`是關鍵。 – 2011-04-08 20:44:26

55

對於EF v4,你可以使用SqlFunctions.StringConvert。所以,你的代碼將結束看起來像這樣:

from s in ctx.Services 
where SqlFunctions.StringConvert((double)s.Code).StartsWith("1") 
select s 

編輯

瑞克在他的評論中提到,將鑄造的int雙(十進制大概也工作)的原因是,該函數沒有int的重載。

1

將IQueryable強制轉換爲IEnumerable,因爲IQueryable繼承IEnumerable。請參見http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx - 具體說明:'枚舉會導致與IQueryable對象關聯的表達式樹被執行。'我認爲重要的是'執行表達式樹的定義'是查詢提供者特有的'。

IQueryable功能非常強大,但在這種情況下被濫用。

1

我嘗試這種解決方法,它的工作對我來說:

from s in ctx.Services 
where (s.Code + "").StartsWith("1") 
select s 

希望這有助於

2

當使用LINQ to對象,你可以使用toString()幫手。

-1
from s in ctx.Services.ToList() 
    where s.Code.ToString().StartsWith("1") 
    select s 
-1
var items = from c in contacts 
select new ListItem 
{ 
    Value = String.Concat(c.ContactId), //This Works in Linq to Entities! 
    Text = c.Name 
}; 

我發現SqlFunctions.StringConvert((雙)C。年齡)沒有爲我工作,無論是字段爲可空類型

在過去的幾天裏,我花了很多搜索試驗和錯誤來找到它。

我希望這可以幫助幾個編碼器。