Web API无法隐式转换类型'System.Collections.Generic.List <<匿名类型:=“”

时间:2018-06-28 10:11:04

标签: c# list linq asp.net-web-api

=“”

我正在创建{{ 1}}中,我知道有很多问题要问,但是我尝试了他们的解决方案,但对我没有用。我正在声明一个列表,该列表将在列表中的多个位置使用。

Web API

错误是

  

无法隐式转换类型'System.Collections.Generic.List <<匿名类型:字符串MSN,System.DateTime? PingDateTime,字符串PingValue,int >> >>到'System.Collections.Generic.List '

如何摆脱这个错误?

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

选项1

您可以从一开始就不声明mainDetails,例如:

public HttpResponseMessage GetDetails(string msn, DateTime dt)
{
    try
    {
        int mainCount = giveMainCount(msn, dt);

        if (mainCount == 0)
        {
            return Request.CreateResponse(HttpStatusCode.OK, new { details = null });
        }

        int mainInterval = mainCount / 500;

        var mainDetails = kesc.tj_xhqd
                        .AsNoTracking()
                        .Where(m => (m.zdjh == msn) && (m.sjsj >= dt))
                        .AsEnumerable()
                        .Select((x, i) => new { MSN = x.zdjh, PingDateTime = x.sjsj, PingValue = x.xhqd, i = i })
                        .Where(x => x.i % mainInterval == 0)
                        .ToList();

        return Request.CreateResponse(HttpStatusCode.OK, new { details = mainDetails });

    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
    }
}

这样做,mainDetails就是您想要的,List是具有别名的匿名类型。


选项2

作为另一种选择,您可以为别名创建一个类(使用所需的内容代替AliasClassName):

public class AliasClassName
{
    public string MSN { get; set; }
    public Nullable<System.DateTime> PingDateTime { get; set; }
    public string PingValue { get; set; }
    public int i { get; set; }
}

然后声明mainDetails作为其中的List

var mainDetails = new List<AliasClassName>();

然后执行:

.Select((x, i) => new AliasClassName { MSN = x.zdjh, PingDateTime = x.sjsj, PingValue = x.xhqd, i = i })

答案 1 :(得分:1)

我找到了一种解决方案,它对我有用

已更改

var mainDetails= new List<tj_xhqd>();

收件人

IEnumerable mainDetails= new List<tj_xhqd>();

这样做,我摆脱了错误

有关更多详细信息,请检查here

相关问题