首页 > 解决方案 > C# 如何在 LINQ 查询中访问 SelectListItem 的 Selected 属性的值?

问题描述

我有以下 LINQ 语句,我想知道如何string.Equals在运行时查看运算符中的参数值。谁能告诉我如何设置我的代码,也许使用 avar来做到这一点?

Items = from Item in GetList()
    select new SelectListItem
    {
        Selected = string.Equals(Item.Value, formTypeSelected, StringComparison.IgnoreCase),
        Text = Item.Key,
        Value = Item.Value                               
    };

标签: c#linq

解决方案


这是因为查询返回的执行IEnumerable被推迟了,所以除非你请求数据,否则你不会得到这么多,例如当你转换它时ToList<T>

Items = (from Item in GetList()
    select new SelectListItem
    {
        Selected = string.Equals(Item.Value, formTypeSelected, StringComparison.IgnoreCase),
        Text = Item.Key,
        Value = Item.Value                               
    }).ToList();

推荐阅读