Question

I have two lists of classes - 'deliveries' and 'pickups' - and I'm trying to make a third list which would add deliveries and pickups together, ie a list to display ALL deliveries AND pickups instead of one or the other.

After searching for a bit, I tried this:

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

but I just get errors saying this:

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

and this:

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

What does this mean, and how can I fix it?

Thanks.

Edit: currently the user inputs the data through a windows form. Deliveries had two String and a TimeSpan, Pickups inherits from Deliveries but also has two more Strings.

    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;
    }
Was it helpful?

Solution

The error message suggests that listDeliveries and listPickups are methods, not variables. So you'll need to call the methods. At the same time, I would strongly suggest that you rename your methods to follow .NET naming conventions. So you might have:

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

Or using LINQ:

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

OTHER TIPS

I would suggest rewoking the thing like this:

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top