-2

I have the following code where i'm trying to split a string and add it to my List of String. But i'm having trouble doing it like this:

List<string> filteredProviders = new List<string>();

foreach (Door2MoreLeadModel d2m in lstDoor2MoreLeadModel)
{
    if(!string.IsNullOrEmpty(d2m.FilteredProviders))
    {                     
        filteredProviders.Add(d2m.FilteredProviders.Split(',')).ToList());
    }
}

Getting following error:

The best overloaded method match for System.Collections.Generic.List.Add(string)' has some invalid arguments

What am I doing wrong?

Huma Ali
  • 1,759
  • 7
  • 40
  • 66
  • 3
    Use `AddRange`. – Patrick Hofman Oct 22 '18 at 12:03
  • The error message is telling you that the method you're trying to call expects you to give it a single string, not a list. The method signature saying "string") should make this clear to you. So to add all the strings from the list you need to use AddRange, as mentioned by others. Or, if you only intended to use one of the bits of the split string, then choose that specific item from the array and pass it to the Add method. It's not quite clear what your actual intent was. – ADyson Oct 22 '18 at 12:04

2 Answers2

3

Use AddRange() instead of Add(), Split() returns an array of strings and ToList is a List<T>, but Add() method accepts just string.

filteredProviders.AddRange(d2m.FilteredProviders.Split(',')).ToList());

even without ToList():

filteredProviders.AddRange(d2m.FilteredProviders.Split(',')));

References: List.Add(T) Method, List.AddRange(IEnumerable) Method

SᴇM
  • 7,024
  • 3
  • 24
  • 41
1
filteredProviders.Add(d2m.FilteredProviders.Split(',')[0]).ToList());

or

filteredProviders.Add(d2m.FilteredProviders.Split(',')[1]).ToList());

By split() you create array of strings and you have to choose which to use.

Or use all of them

filteredProviders.AddRange(d2m.FilteredProviders.Split(',')).ToList());
Tomáš Filip
  • 727
  • 3
  • 6
  • 23