从IEnumerable C#返回列表<object>

时间:2016-04-15 11:45:21

标签: c# ienumerable tolist

我有一个方法:

public List<AxeResult> LoadAxes(string kilometriczone, string axe)
{
    IEnumerable<AxeResult> allAxes = PullAxes();
    var findAxes = allAxes.Select(a => a.KilometricZone.StartsWith(kilometriczone) || a.KilometricZone.StartsWith(axe));

    return findAxes.Cast<AxeResult>().ToList();
}

我有这个错误:

  

IEnumerable<bool>不包含ToListEnumerable.ToList<AxeResult>的定义   最好的扩展方法重载IEnumerable<AxeResult>(   IEnumerable<AxeResult>)需要受体类型DECLARE @CustomerID INT = 100; -- SAMPLE DATA FOR CUSTOMERS DECLARE @Customers TABLE (ID INT, Name VARCHAR(255), ParentID INT); INSERT @Customers (ID, Name, ParentID) VALUES (100, 'Customer A', NULL), (101, 'Customer B', NULL), (102, 'Customer C', 100), (103, 'Customer D', 100), (104, 'Customer E', 101); -- SAMPLE DATA FOR TICKETS DECLARE @Tickets TABLE (ID INT, Name VARCHAR(255), ParentID INT); INSERT @Tickets (ID, Name, ParentID) VALUES (500, 'Ticket A', 100), (501, 'Ticket B', 100), (502, 'Ticket C', 102), (503, 'Ticket D', 102), (504, 'Ticket E', 103), (505, 'Ticket F', 101), (506, 'Ticket G', 104), (507, 'Ticket H', 101); -- USE RECURSIVE CTE TO LOOP THROUGH HIERARCHY AND GET ALL ANCESTORS WITH RecursiveCustomers AS ( SELECT c.ID, c.Name, c.ParentID FROM @Customers AS c UNION ALL SELECT rc.ID, rc.Name, c.ParentID FROM RecursiveCustomers AS rc INNER JOIN @Customers AS c ON rc.ParentID = c.ID ) SELECT t.ID, t.Name, t.ParentID FROM @Tickets AS t INNER JOIN RecursiveCustomers AS rc ON rc.ID = t.ParentID WHERE rc.ParentID = @CustomerID OR (rc.ID = @CustomerID AND rc.ParentID IS NULL);

我想在搜索操作后返回一个AxeResult列表。

2 个答案:

答案 0 :(得分:6)

您想要的是过滤集合。这是Enumerable.Where的用途:

public List<AxeResult> LoadAxes(string kilometriczone, string axe)
{
    return PullAxes()
        .Where(a => a.KilometricZone.StartsWith(kilometriczone) || 
                    a.KilometricZone.StartsWith(axe))
        .ToList();
}

答案 1 :(得分:2)

除了给出的答案之外还有一些解释:

其中()方法的作用类似于过滤器,并返回同一组的子集

选择()方法进行投影并返回新设置

关于.Select()和Where()方法here之间的差异有全面的解释。