【问题标题】:How to perform LINQ on IEnumerable<Employee> / IEnumerable<object>?如何在 IEnumerable<Employee> / IEnumerable<object> 上执行 LINQ?
【发布时间】:2015-04-06 06:40:39
【问题描述】:

我有

IEnumerable<Employee> GetAllEmployees()
{
  return Get<IEmployeeRepository>().GetAll();
}

IEmployeeRepository 在哪里

public interface IEmployeeRepository
    {
        IEnumerable<Employee> GetAll();  
    }

Employee.cs如下

public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }        
        public int Age { get; set; }
        public int Salary { get; set; }
    }

现在我想根据传递的 EmployeeId 对从 GetAllEmployees() 获得的记录执行搜索。如下所示

public void SearchEmployee(int empId)
        {
            var empRecords = this.GetAllEmployees();
            var filteredRecords = empRecords.
        }

我实际上查看了this 的答案,但无法满足要求。 我需要做什么?

【问题讨论】:

  • 可能是您缺少顶部 using System.Linq 的命名空间声明。还要记住IEnumerable 不支持不同的执行,例如IQuerable
  • 如果将var empRecords = this.GetAllEmployees(); 更改为IEnumerable&lt;Employee&gt; empRecords = this.GetAllEmployees(); 会怎样?
  • @Jenish Rabadiya,非常棒。我刚刚在我的命名空间中看到了它。
  • @JenishRabadiya IEnumerable 不支持像 IQuerable 那样的不同执行 是什么意思。 IEnumerable 支持延迟执行。事实上Enumerable.WhereSelect等都是懒惰的。

标签: c#


【解决方案1】:

我刚刚发现命名空间 System.Linq 丢失了。 否则我们甚至可以做

foreach (var item in empRecords)
{
   //
}

我会把功劳归功于@Jenish Rabadiya,尽管其他人也给出了正确的意见。

【讨论】:

  • Jenish Rabadiya 没有想到这一点吗?
  • 我已经提到过 (:. 并感谢他。(:
  • 我认为杰尼什应该回答这个问题,然后他就会得到他应得的“功劳”;)
【解决方案2】:

这是您首先需要转换为对象列表然后尝试强制转换的对象。

 (empRecords as IEnumerable<object>).Cast(....)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多