将List <t> .add()添加到另一个列表


134

我有一个IEnumerable<TravelDetails>,我正在尝试将for-loop中的值添加到a中List<TravelDetails>。我不断收到错误消息。

错误15参数1:无法从'System.Collections.Generic.List'转换为'TrafficCore.DataObjects.TripDetails'C:\ TrafficNew \ TI 511-Web \ Traffic 2.0 \ 511Traffic \ 511Traffic \ Models \ DrivingTime.cs

我的代码是

List<TripDetails> tripDetailsCollection = new List<TripDetails>();
foreach (DrivingTimeRoute dtr in dtRoutes)
{
    foreach (Trip trip in dtr.Trips)
    {
        foreach (TripPathLink tpl in trip.TripPathLinks)
        {
            tplCollection.Add(tpl);
        }
        IEnumerable<TripDetails> tripDetails = //long Linq-to-Sql here
        List<TripDetails> td = tripDetails.ToList();
        tripDetailsCollection.Add(td); // <<< Error here
    }
}

有人可以帮我弄这个吗。
谢谢Pawan


您能告诉错误发生在哪一行吗?
R. Martinho Fernandes

Answers:


269

List<T>.Add添加一个元素。而是使用List<T>.AddRange添加多个值。

此外,List<T>.AddRange使用IEnumerable<T>,因此您无需转换tripDetailsList<TripDetails>,可以直接传递它,例如:

tripDetailsCollection.AddRange(tripDetails);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.