c# - LINQ 搜索包含带有对象的类的列表

标签 c# list linq class search

我是 C# 的新手,我知道如何对具有一个 字段/类型的列表进行 LINQ 搜索,但不知道如何使用许多 类型的对象。我创建了一个列表

List<Reader> results = new List<Reader>();

包含这个类的:

public class Reader
{

    public int ID { get; set; }
    public string Name { get; set; }
    public string Course { get; set; }
    public int Grade { get; set; }

    public Reader(int id, string name, string course, int grade)
    {
        ID = id;
        Name = name;
        Course = course;
        Grade = grade;
    }
}

我想用 LINQ 搜索它并匹配进入该站点的用户的 IDName。 如果这两个字段相同,我想从列表中获取用户 CourseGrade

有什么建议吗?

最佳答案

一个简单的 Where condition(s)Select representation 应该做的:

 List<Reader> results = ...

 var data = results
   .Where(item => item.ID == userID && item.Name == userName)
// .OrderBy(item => item.Course) // uncomment if you want to order by course
   .Select(item => $"Course: {item.Course} Grade: {item.Grade}");

 foreach (var record in data)
   Console.WriteLine(record);

关于c# - LINQ 搜索包含带有对象的类的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56492905/

相关文章:

c# - 我可以为我不直接控制的两个类添加隐式转换吗?

c# - 如何在 Ubuntu 上运行依赖于 NuGet 包的 .net Core 应用程序

c# - 在字符串 :string dictionary where a given filter string is a subset of the key string 中查找值

通用列表中的 C-Void 指针(包含结构)

c# - 是否有一种 LINQ 方法可以执行类似 foreach 的操作然后调用函数?

c# - WPF 设计器无法找到 SQLite.Interop.dll

python - 从Python 3移至Python 2

list - 检查列表是否是回文。如果没有,插入元素使其成为回文。 (序言)

linq - Linq Take()问题

c# - 使用 LINQ 从 IGrouping 中选择特定元素