You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC中List<dynamic>使用LINQ Where查询失败求助

解决ASP.NET MVC中List使用LINQ Where筛选失败的问题

嘿,我来帮你搞定这个问题!你遇到的LINQ筛选失败情况,核心原因出在dynamic类型的特性上——编译时编译器不会检查a.postBlogType这个属性是否存在,只有运行时才会验证。如果API返回的对象里没这个属性、属性名/类型和你预期的不匹配,直接就会抛出异常。

下面给你几个可行的解决方案,按推荐程度排序:

方案1:用强类型替代dynamic(强烈推荐)

这是最稳妥的做法,能彻底避免这类运行时坑。你只需要定义一个和API返回结构对应的实体类,把dynamic换成这个强类型,编译时就能检查属性对错,还能享受到智能提示。

比如先定义Blog实体:

public class BlogWithUser
{
    // 要和API返回的字段名完全匹配,或者用JsonProperty特性映射
    public string postBlogType { get; set; }
    // 别忘了加上API返回的其他属性,比如博客ID、标题、作者名等
    public int BlogId { get; set; }
    public string Title { get; set; }
    // ...其他属性
}

然后修改你的getallBlogs方法返回类型:

private List<BlogWithUser> getallBlogs()
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            // 替换成你的API地址
            var response = await client.GetAsync("https://your-api-url/blogs");
            response.EnsureSuccessStatusCode(); // 确保请求成功
            var jsonContent = await response.Content.ReadAsStringAsync();
            // 反序列化为强类型集合
            return JsonConvert.DeserializeObject<List<BlogWithUser>>(jsonContent);
        }
    }
    catch (Exception ex)
    {
        // 自定义异常处理逻辑,比如打日志、返回空列表
        Console.WriteLine($"获取博客列表失败:{ex.Message}");
        return new List<BlogWithUser>();
    }
}

这时候你的筛选代码就能正常运行了:

ViewData["AuthorBlogs"] = allblogswithuser.Where(a => a.postBlogType == "2").ToList();

方案2:保留dynamic但做安全检查(仅临时应急用)

如果暂时没法改强类型,那得先确保API返回的每个对象确实有postBlogType属性,再用安全的方式访问它:

方式A:转成ExpandoObject再筛选

ExpandoObject可以让你更安全地检查属性是否存在:

// 先把dynamic集合转成ExpandoObject
var safeBlogs = allblogswithuser.Cast<ExpandoObject>().ToList();

ViewData["AuthorBlogs"] = safeBlogs.Where(blog => 
{
    // 尝试获取postBlogType属性值
    if (blog.TryGetValue("postBlogType", out var typeValue))
    {
        // 转成字符串后和"2"比较,注意处理null情况
        return typeValue?.ToString() == "2";
    }
    // 没有这个属性的话,直接返回false(或按需求处理)
    return false;
}).ToList();

方式B:用反射检查属性

另一种方式是通过反射验证属性存在性并取值:

ViewData["AuthorBlogs"] = allblogswithuser.Where(blog => 
{
    var type = blog.GetType();
    // 检查是否有postBlogType属性
    var property = type.GetProperty("postBlogType");
    if (property != null)
    {
        var value = property.GetValue(blog);
        return value?.ToString() == "2";
    }
    return false;
}).ToList();

原代码失败的常见原因

  1. 属性名不匹配:API返回的字段名可能是PostBlogType(首字母大写)或者blog_type,和你写的postBlogType不一致,运行时会抛出RuntimeBinderException。
  2. 类型不匹配:如果API返回的postBlogType是int类型(比如2而不是"2"),用字符串"2"比较会报错。
  3. 对象结构问题:API返回的可能是嵌套结构,比如a.Blog.postBlogType,你直接访问a.postBlogType当然找不到。

内容的提问来源于stack exchange,提问作者TAHA SULTAN TEMURI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:05:07