1

所以我有点卡在下面的 linq 语句上,

        public void ReturnHire(string carregistration, string hirefromdate, string hiretodate)
        {
            var result = customermembers.Where(c => c.CustomerCarType.Where(n => String.Equals(n.CarRegistration, carregistration)).FirstOrDefault(); // this line
            if (result != null)
            {
                customermembers.ForEach(c => c.CustomerHireDate.RemoveAll(cs => cs.HireFromDate == hirefromdate && cs.HireToDate == hiretodate));
                customermembers.ForEach(c => c.CustomerCarType.RemoveAll(cs => cs.CarRegistration == carregistration));
            }
        }

我的 xml 看起来像这样:

<ArrayOfCustomer>
    <Customer>
        <CustomerID>1</CustomerID>
        <FirstName>G</FirstName>
        <LastName>Graam</LastName>
        <Age>27</Age>
        <CustomerHireDate>
            <HireDate>
                <HireFromDate>15.07.2012</HireFromDate>
                <HireToDate>29.07.2012</HireToDate>
            </HireDate>
        </CustomerHireDate>
        <CustomerCarType>
            <CarType>
                <CarRegistration>IAWB-OOTO</CarRegistration>
            </CarType>
        </CustomerCarType>
    </Customer>
</ArrayOfCustomer>

在我的客户端,客户要“归还”车辆,对我来说,这基本上只是从日期和日期中删除租用,并从客户内部删除注册号。但这是我必须只用注册号进行删除的问题,所以我试图在 where 子句中做一个 where 但它说我不能将 CarType 隐式转换为 bool。

我的网络服务有这些列表:

        List<Customer> customermembers = new List<Customer>();
        List<HireDate> hiredates = new List<HireDate>();
        List<CarType> cartypes = new List<CarType>();

我只是觉得customermembers where customer car type where rehistration number equals mystring会很好?

4

1 回答 1

1

由于您实际上并未result在 if 块中使用,因此您可以这样做:

    public void ReturnHire(string carregistration, string hirefromdate, string hiretodate) 
    { 
        if (customermembers.Any(c => c.CustomerCarType.Any(n => String.Equals(n.CarRegistration, carregistration)))
        { 
            customermembers.ForEach(c => c.CustomerHireDate.RemoveAll(cs => cs.HireFromDate == hirefromdate && cs.HireToDate == hiretodate)); 
            customermembers.ForEach(c => c.CustomerCarType.RemoveAll(cs => cs.CarRegistration == carregistration)); 
        } 
    } 

Any如果至少有一个元素满足谓词,则返回 true。

然而,这并不是非常有效,因为您要迭代列表三次;你应该只迭代一次。我会发布一个示例,但我认为您的代码中有一个错误,我不想重复它。考虑使用相同的hiredfromdate 和hiredtodate 进行单独注册的不同客户。您的代码将删除尚未归还汽车的客户的 CustomerHireDate。

但是,您很可能打算result在 if 块中使用,这应该可以修复错误:

    public void ReturnHire(string carregistration, string hirefromdate, string hiretodate) 
    { 
        var result = customermembers.Where(c => c.CustomerCarType.Any(n => String.Equals(n.CarRegistration, carregistration));
        foreach (var customermember in result)
        { 
            customermember.CustomerHireDate.RemoveAll(cs => cs.HireFromDate == hirefromdate && cs.HireToDate == hiretodate); 
            customermember.CustomerCarType.RemoveAll(cs => cs.CarRegistration == carregistration); 
        } 
    }

请记住,Where这不会更改原始集合,因此您需要迭代result以获取过滤后的对象集。

于 2012-07-26T23:23:47.523 回答