将十进制的linq结果转换为ObservableCollection
尝试将来自LINQ查询的结果存储到ObservableCollection中,但linq的结果是十进制类型。将十进制的linq结果转换为ObservableCollection <string>
ObservableCollection<string> cost =
new ObservableCollection<string>((from i in context.Items
where i.Cost != null
&& i.Cost > 0
orderby i.Cost
select i.Cost).Distinct());
它不会编译说'The best overloaded method match for 'System.Collections.ObjectModel.ObservableCollection<string>.ObservableCollection(System.Collections.Generic.IEnumerable<string>)' has some invalid arguments.
我看着here但它并没有帮助我很多。
UPDATE
我曾尝试没有成功如下:
ObservableCollection<string> cost =
new ObservableCollection<string>((from i in context.Items
where i.Cost != null
&& i.Cost > 0
orderby i.Cost
select i.Cost).Distinct()
.Select(i=>i.ToString()));
和
ObservableCollection<string> cost =
new ObservableCollection<string>((from i in context.Items
where i.Cost != null
&& i.Cost > 0
orderby i.Cost
select i.Cost.ToString()).Distinct());
当我在LINQPad同时运行,我得到以下错误:LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression. Message LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
尝试
ObservableCollection<string> cost =
new ObservableCollection<string>((from i in context.Items
where i.Cost != null
&& i.Cost > 0
orderby i.Cost
select i.Cost).Distinct()
.AsEnumerable()
.Select(c => c.ToString()));
由于显然EF提供商似乎无法翻译ToString()
调用到SQL,投入到AsEnumerable()
一个来电,将会带给查询到内存和ToString()
通话将使用LINQ到对象。
转换Cost
到字符串ToString
:
ObservableCollection<string> cost =
new ObservableCollection<string>((from i in context.Items
where i.Cost != null
&& i.Cost > 0
orderby i.Cost
select i.Cost.ToString()).Distinct());
使用任何CultureInfo
你的需要,如果有的话,称ToString()
时。
为什么不使用ToString()?
ObservableCollection<string> cost =
new ObservableCollection<string>((from i in context.Items
where i.Cost != null
&& i.Cost > 0
orderby i.Cost
select i.Cost.ToString()).Distinct());
您应该context.Items
选择字符串值铸造他们创造一个ObservableCollection<string>
到String
ObservableCollection<string> cost =
new ObservableCollection<string>((from i in context.Items
where i.Cost != null
&& i.Cost > 0
orderby i.Cost
select i.Cost.ToString()).Distinct());
或创建一个ObservableCollection<decimal>
ObservableCollection<decimal> cost =
new ObservableCollection<decimal>((from i in context.Items
where i.Cost != null
&& i.Cost > 0
orderby i.Cost
select i.Cost).Distinct());
我尝试了你的第一个建议,但是我得到了与我在Weston的文章中评论过的结果相同的结果。不幸的是我不能使用小数点ObservableCollection。 – Robert 2013-03-27 16:04:34
执行ToString
的Distinct
后。这样它就不会创建这么多的字符串,并且可以比较不同的字符串。
ObservableCollection<string> cost =
new ObservableCollection<string>((from i in context.Items
where i.Cost != null
&& i.Cost > 0
orderby i.Cost
select i.Cost).Distinct()
.Select(i=>i.ToString()));
我试过这个,但是当我运行它时,它会默默地崩溃。如果我在它上面放置一个断点并尝试插入它,那么程序会继续运行并跳过其余代码(如表单加载但集合中没有任何内容)。 – Robert 2013-03-27 16:02:58
感谢迈克....这工作完美! – Robert 2013-03-27 17:43:34