我有以下课程作为清单;
class list_TA
{
public DateTime SAMPLE_TIME { get; set; }
public string WAIT_CLASS { get; set; }
public double COUNT { get; set; }
public list_TA(DateTime SAMPLE_TIME, string WAIT_CLASS,double COUNT)
{
this.SAMPLE_TIME = SAMPLE_TIME;
this.WAIT_CLASS = WAIT_CLASS;
this.COUNT = COUNT;
}
}
//SECOND PART
var test = listASH
.Select(g => new
{
SAMPLE_TIME = statiClass.By15Seconds(Convert.ToDateTime(g.SAMPLE_TIME)),
WAIT_CLASS = g.WAIT_CLASS,
COUNT = 0,
}).GroupBy(x => new { x.SAMPLE_TIME, x.WAIT_CLASS })
.Select(y => new
{
SAMPLE_TIME = y.Key.SAMPLE_TIME,
WAIT_CLASS = y.Key.WAIT_CLASS,
COUNT = Math.Round(y.Count() / 15.0, 2),
});
我想要的是将linq结果加载到list_TA中。但是下面的代码不起作用,并且会出现以下错误;
List<list_TA> lst = (List<list_TA>)test.ToList();
错误;
Cannot convert type 'System.Collections.Generic.List<<anonymous type: System.DateTime SAMPLE_TIME, string WAIT_CLASS, double COUNT>>' to 'System.Collections.Generic.List<vodaMon.list_TA>'
转换ToList();没用。
答案 0 :(得分:2)
在匿名类不能被隐式转换为任何其它类型。
您需要使用new list_TA
而不是new
将默认构造函数添加到您的list_TA
类中,并使用下面的代码
.Select(y => new list_TA
{
SAMPLE_TIME = y.Key.SAMPLE_TIME,
WAIT_CLASS = y.Key.WAIT_CLASS,
COUNT = Math.Round(y.Count() / 15.0, 2),
});
或
.Select(y => new list_TA (
y.Key.SAMPLE_TIME,
y.Key.WAIT_CLASS,
Math.Round(y.Count() / 15.0, 2)
));
答案 1 :(得分:2)
还使用new list_TA
代替任意类型:
实例化list_TA时,它需要DateTime SAMPLE_TIME,字符串WAIT_CLASS,双COUNT作为参数传递。为了解决这个问题,请引入无参数构造函数。
public class list_TA
{
public DateTime SAMPLE_TIME { get; set; }
public string WAIT_CLASS { get; set; }
public double COUNT { get; set; }
public list_TA()
{
}
public list_TA(DateTime SAMPLE_TIME, string WAIT_CLASS, double COUNT)
{
this.SAMPLE_TIME = SAMPLE_TIME;
this.WAIT_CLASS = WAIT_CLASS;
this.COUNT = COUNT;
}
}
答案 2 :(得分:1)
您可以像下面这样在LINQ中选择list_TA:
var test = listASH
.Select(g => new
{
SAMPLE_TIME = statiClass.By15Seconds(Convert.ToDateTime(g.SAMPLE_TIME)),
WAIT_CLASS = g.WAIT_CLASS,
COUNT = 0,
}).GroupBy(x => new { x.SAMPLE_TIME, x.WAIT_CLASS })
.Select(y => new list_TA
{
SAMPLE_TIME = y.Key.SAMPLE_TIME,
WAIT_CLASS = y.Key.WAIT_CLASS,
COUNT = Math.Round(y.Count() / 15.0, 2),
}).ToList();