我在IEnumerable(C#3.0)中做了什么错

时间:2010-06-04 06:57:56

标签: linq c#-3.0 anonymous-types

如果我写

var v = (from r in stock.ReplacementLog
                                             select new 
                                             {
                                                 AssetId = stock.AssetId,
                                                 Date = stock.ReferDate,
                                                 FactType = r.Key,
                                                 Value = r.Value
                                             });

工作正常......

但如果我这样做

IEnumerable<StockAsset> v = (from r in stock.ReplacementLog
 select new  {
 AssetId = stock.AssetId,
Date = stock.ReferDate,
FactType = r.Key,
Value = r.Value });

我收到错误:

无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'System.Collections.Generic.IEnumerable'。存在显式转换(您是否缺少演员?)

然后我做了

IEnumerable<StockAsset> v = 
(
from r in stock.ReplacementLog
select new
{
AssetId = stock.AssetId,
Date = stock.ReferDate,
FactType = r.Key,
Value = r.Value
}).ToList<StockAsset>();

出现以下一堆错误:

错误1实例参数:无法从'System.Collections.Generic.IEnumerable'转换为'System.Collections.Generic.IEnumerable'

错误2'System.Collections.Generic.IEnumerable'不包含'ToList'的定义和最佳扩展方法重载'System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable)'有一些无效的论点

然后我尝试了

IEnumerable<StockAsset> v1 = 
(from r in stock.ReplacementLog
select new StockAsset 
{
AssetId = stock.AssetId,
ReferDate= stock.ReferDate,
FactType = r.Key,
Value = r.Value
}); 

有错误:     错误1     'StockAsset'不包含'FactType'的定义

**Error 2
'StockAsset' does not contain a definition for Value'** 

StockAsset类位于

之下
public class StockAsset
{
        public int AssetId { get; set; }
        public DateTime ReferDate {get;set;}        
        public Dictionary<EnumFactorType, double> ReplacementLog { get; set; }   
}

需要帮助。

使用C#3.0

由于

3 个答案:

答案 0 :(得分:2)

写作时

select new  {
 AssetId = stock.AssetId,
 Date = stock.ReferDate,
 FactType = r.Key,
 Value = r.Value }

您实际上是生成匿名类型。您无法将此匿名类型强制转换为声明的类型。

如果你想创建一个你应该做的类的对象

 select new StockAsset
 {
     AssetId = ..., // Maybe stock.AssetId
     ReferDate = ..., // Maybe stock.ReferDate
     ReplacementLog = ... // Maybe new Dictionary<string, short> { {r.Key, r.Value} };
 }

答案 1 :(得分:0)

写作时

select new { property = value }

您正在创建一个新的匿名类型的实例,而您似乎想要实际创建StockAsset,因此您需要

select new StockAsset { property = value }

答案 2 :(得分:0)

我最好的猜测是,您正在尝试为另一个StockAsset的ReplacementLog中的每个条目创建一个新的StockAsset。这个新的StockAsset将在其ReplacementLog中有一个条目。它是否正确?如果是这样,您可以在StockAsset上创建一个新的构造函数:

public StockAsset(int assetId, DateTime referDate, 
                  EnumFactorType factorType, double value)
{
    AssetId = assetId;
    ReferDate = referDate;
    ReplacementLog = new Dictionary<EnumFactorType, double>();
    ReplacementLog[factorType] = value;
}

然后在LINQ中调用该构造函数。

IEnumerable<StockAsset> v = (from r in stock.ReplacementLog
    select new StockAsset(stock.AssetId, stock.ReferDate, r.Key, r.Value));