不能在匿名类型中使用string.Format()

时间:2012-03-27 19:48:47

标签: anonymous-types 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);

但是,它在尝试绑定到DataSource时会出现以下错误:

  

“LINQ to Entities无法识别方法'System.String   格式化(System.String,System.Object,System.Object)'方法,以及此方法   方法无法转换为商店表达式。“

有没有办法在匿名类型中包含像string.Format()这样的方法?

1 个答案:

答案 0 :(得分: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的调用将导致从数据库加载项目,您的格式现在将正确执行。