合并两个列表以制作第三个列表 - 错误

时间:2012-12-01 23:54:20

标签: c# list addrange

我有两个班级列表 - '交付'和'拾取' - 我正在尝试制作第三个列表,它会将交付和拾取加在一起,即显示所有交付和取件的列表,而不是一个或者其他

搜索了一下后,我试了一下:

public List<String> listVisits()
    {
        List<String> listVisits = new List<string>();
        listVisits.AddRange(listDeliveries);
        listVisits.AddRange(listPickups);
    }

但我只是错误地说:

The best overloaded method match for 'System.Collections.Generic.List<string>.AddRange(System.Collections.Generic.IEnumerable<string>)' has found some invalid arguments

和此:

Argument 1: cannot convert from 'method group' to 'System.Collections.Generic.IEnumerable<string>'

这是什么意思,我该如何解决?

感谢。

编辑:目前用户通过Windows窗体输入数据。 Deliveries有两个String和一个TimeSpan,Pickups继承自Deliveries,但还有两个字符串。

    public List<String> listDeliveries()
    {
        List<String> listDeliveries = new List<string>();
        foreach (deliveries Deliv in delivery)
        {
            String DelivAsString = Deliv.DeliveryString();
            listDeliveries.Add(DelivAsString);
        }
        return listDeliveries;
    }

    public List<String> listPickups()
    {
        List<String> listPickups = new List<string>();
        foreach (pickups Pickup in pickup)
        {
            String PickupAsString = Pickup.PickupString();
            listPickups.Add(PickupAsString);
        }
        return listPickups;
    }

2 个答案:

答案 0 :(得分:6)

错误消息表明listDeliverieslistPickups方法,而不是变量。所以你需要调用这些方法。同时,我强烈建议您重命名方法以遵循.NET命名约定。所以你可能有:

public List<String> ListVisits()
{
    List<String> visits = new List<string>();
    visits.AddRange(ListDeiveries());
    visits.AddRange(ListPickups());
    return visits;
}

或使用LINQ:

public List<String> ListVisits()
{
    return ListDeliveries().Concat(ListPickups()).ToList();
}

答案 1 :(得分:0)

我建议你重写这样的事情:

public List<string> GetDeliveryStrings()
{
    //assuming "deliveries" is your collection of deliveries 
    //otherwise your coding standards are not, well, standard
    //additionally, per Tim Schmelter's suggestion, take a look at 
    //overriding the .ToString() method
    return deliveries.Select(d => d.DeliveryString()).ToList()
}

public List<String> GetPickupStrings()
{
    return pickups.Select(p => p.PickupString()).ToList();
}

//lifted from Jon Skeet's answer
public List<String> GetVisitStrings()
{
   return GetDeliveryStrings().Concat(GetPickupStrings()).ToList();
}