c# - ListItemCollection - 使用 LINQ 从值中获取文本

标签 c# linq

我有 ListItemCollection。每个元素都是 ListItem 类型。我只想返回具有给定值的项目的文本。

目前,我正在使用这个功能:

public string GetTextFromPaymentWayCollection(string value)
{
  ListItemCollection listPaymentWays = DB.GetList();

  foreach (ListItem item in listPaymentWays)
  {
    if (item.Value == value)
    {
      return item.Text;
    }
  }
  return null;
}

有没有办法用 LINQ 来代替这个函数来做到这一点?

最佳答案

你的 listPaymentWays属于 ListItemCollection 没有实现 IEnumerable<T> . linq 方法是 IEnumerable<T> 上的扩展方法.

例如 FirstOrDefault 的签名:

public static TSource FirstOrDefault<TSource>(
    this IEnumerable<TSource> source
)

首先要做的是Cast (这将返回一个 IEnumerble<ListItem> )然后使用 FirstOrDefault :

var result = listPaymentWays.Cast<ListItem>()
                            .FirstOrDefault(x => x.Value == value)?.Text;

?.是 C# 6.0 Null Proparation 功能。


我还建议 DB.GetList()将公开一个将获取值的方法,以便过滤将在数据库中而不是在内存中进行。带上所有的数据很浪费,创建ListItems然后只取一个项目。

关于c# - ListItemCollection - 使用 LINQ 从值中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40425966/

相关文章:

c# - 项目命令无法编辑列表中的其他项目

c# - 以某种方式排序的日期列表

c# - 为什么 Entity Framework 6 会为简单查找生成复杂的 SQL 查询?

c# - 从通用 List<t> 中删除项目

c# - 在 WPF 中使用另一个页面上的现有 Canvas

c# - 无法在 Unity3D 中移动实例化的预置

c# - 如何在 Resharper 4.5 中使用 bdd 命名风格?

c# - SyndicationFeed AttributeExtensions 命名空间前缀

c# - 选择模型属性包含所有键值对列表的位置

c# - 一个或另一个列表中的一组值,但不是两个