2012-03-27 73 views
0

我希望能實現的東西如下:不能在匿名類型使用的String.format()

var comboBoxItems = from state in states 
       select new 
       { 
        Key = state.Code, 
        Value = string.Format("{0} ({1})", state.Name, state.Code) 
       }; 

this.stateComboBox.DisplayMember = "Value"; 
this.stateComboBox.ValueMember = "Key"; 
this.stateComboBox.DataSource = new BindingSource(comboBoxItems, null); 

但是,它給了我下面的錯誤,當它試圖綁定到數據源:

「LINQ實體無法識別方法‘System.String 格式(System.String,System.Object的,System.Object的)’方法,和這種方法 不能被翻譯成表達店」。

有什麼辦法可以像匿名類型中的string.Format()方法?

回答

0
var comboBoxItems = from state in states.ToList() 
       select new 
       { 
        Key = state.Code, 
        Value = string.Format("{0} ({1})", state.Name, state.Code) 
       }; 

不能使用在LINQ 2個實體Format,因爲它不能被轉換爲SQL。調用ToList將導致項目從數據庫加載,您的格式現在將正確執行。

+0

完美,謝謝! – lintmouse 2012-03-27 20:05:52