开发者

List<T> add method in C#

As I know. List Add method works as below.

List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");

If I designed the data structure as this

List<object> lstObj = new List<object>();            
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here 
{
    List开发者_Go百科<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}

Does the List Add method works or not if I add different types members in the same function.


You can't add a List<object> to a List<string>. The only thing you can add to list of strings is strings (or null references). You could use this instead:

List<object> cities = new List<object>();

But this seems like a bad design. When you use object as the generic type of a collection you effectively lose all the benefits of type-safety.

For parsing XML I'd suggest you look at XmlDocument.


Since you created a list of type object you can add anything to it since every type can be boxed into an object.


You can add anything to a List<object>, so if you changed cities to a List<object> then your code would work.

var list = new List<object>();

list.Add("hello");
list.Add(1);
list.Add(new List<bool>());

Console.WriteLine(list.Count());

Having said that, it's almost certainly a bad way to code whatever it is you're trying to do.


List<object> AListObject = new List<object>();
foreach (object o in AListObject)
{
    string s = o as string;
    if (s != null)
    {
        cities.Add(s);
    }
}

If you could use LINQ from .NET 3.5 than you could do next:

List<object> AListObject = new List<object>();
cities.AddRange(AListObject.OfType<string>());


There's no point using a generic list with object as the type parameter, might as well use a System.Collections.ArrayList.


You should use the List.AddRange method for adding multiple items to a list.

cities.AddRange(AListObject);

However, you'll have problems trying to add object to a list of string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜