How to cast two List...
I want something like that
List<Obj1> list = new List<Obj1>();
list.add(new Obj1);
List<Obj2> list2 = new List<Obj2>();
list2.add((Obj1)list[0]);
You may be interested in the Enumerable extension method Cast.
IEnumerable<Obj2> enumerable = list.Cast<Obj2>();
You can then convert to List if necessary:
var list2 = enumerable.ToList()
(This obviously assume the cast from Obj1 to Obj2 is valid: that Obj2 derives from Obj1 or that a conversion operator exists.)
I'm not sure what you are trying to do but it might be something like this
var nums = new List<int> {3,1,4,1,5,9,2,6,5};
var words = new List<string> {"Do", "not", "disturb", "my", "circles"};
words.AddRange(nums.Cast<string>());
To add a single element, your code would work, provided you fix the syntax:
List<Obj1> list = new List<Obj1>();
list.Add(new Obj1());
List<Obj2> list2 = new List<Obj2>();
list2.Add((Obj1)list[0]);
To concatenate the the whole list you can replace the last line with list2.AddRange(list.Cast<Obj1>());
Related
I wanted to know if i have few list obejcts in my code, if i want to declare all the lists in one line is it equal to declaration in seperate lines:
ListA = ListB = ListC ... = new List<MyType>();
is it equal to:
ListA = new List<MyType>();
ListB = new List<MyType>();
ListC = new List<MyType>();
...
I must be sure i will have no aliasing issue that way
as Flydog57 commented out, the assignment reffers to the same object in the 1st example,
and create new instance on the 2nd example.
I was asked this question today:
How can I add an item to a list and return that list back?
The code for List<T>.Add(T) returns void. So you can't do something like this:
var list = new List<string>{"item1","item2"};
var newList = list.Add("item3");
This is related to using AutoMapper, although that part isn't particularly important.
One option is Linq, with Concat:
var list = new List<string>{"item1", "item2"};
var newList = list.Concat(new[] { "item3" }).ToList();
In typical Linq fashion, list stays the same, and newList contains all the items from list as well as the items in the new list, in this case just "item3".
You can skip the .ToList() to keep the IEnumerable<string> result if that fits your use case.
If you find yourself doing this often with individual items, you can use something like this extension method to pass them without the new[] { ... } syntax:
public static IEnumerable<T> ConcatItems<T>(this IEnumerable<T> source, params T[] items)
{
return source.Concat(items);
}
Because of the params array the earlier example becomes:
var list = new List<string>{"item1", "item2"};
var newList = list.ConcatItems("item3").ToList();
Make sure not to mix this up with Union, which removes duplicate items. (Searching for those duplicates is overhead that you probably don't want!)
The answer to this question was relatively simple:
var list = new List<string>(new List<string>{"item1","item2"}){"item3"};
List<T>() has a constructor that can take in IEnumerable<T> (MSDN). Additionally, you can use the object setter to put new items into the list.
So, for a more complicated example:
var originalList = new List<string>();
originalList.Add("item1");
originalList.Add("item2");
var newList = new List<string>(originalList){"item3"};
You can simply do :
List<string> list = new List<string>{"item1","item2"};
List<string> newList = null;
(newList = list.ToList()).Add("item3");
Or create your own extension method :
public static class Helper
{
public static List<T> MyAdd<T>(this List<T> collection, T item)
{
collection.Add(item);
return collection;
}
}
And use it :
List<string> list = new List<string>{"item1","item2"};
List<string> newList = list.MyAdd("item3"); // same object though
List<string> newList2 = newList.ToList().MyAdd("item4").MyAdd("item5"); // different object
One property of an ImmutableList<T> (and other similar data structures from System.Collections.Immutable) is that it doesn't mutate the original list, it returns another immutable list with the added value.
So doing this:
var originalImmutable = ImmutableList<int>.Create(1, 2);
var otherImmutable = originalImmutable.Add(3);
Will result in a shallow copied new list each time you call Add.
The most readable and maintainable solution is to copy the list and then add the item:
var list = new List<string>{"item1","item2"};
var newList = list.toList();
newList.Add("item3");
Seven years have passed since the question has been asked but Enumerable class now offers Prepend and Append methods that could be used in a straightforward fashion:
var list = new List<string>{"item1","item2"};
var newList = list.Append("item3").ToList();
I just want to know the difference between List<string> lst = new List() and List<> lst = new List()
There is no List type. List<T> (or List(Of T) in VB) is a generic. It means that the list can only hold a type you pass in.
For instance:
List<string> list1 = new List<string>();
list1.Add("hello"); // OK
list1.Add(123); // Compiler error
List<int> list2 = new List<int>();
list2.Add("hello"); // Compiler error
list2.Add(123); // OK
You can read more about the generic list at MSDN.
If you want an un-typed list, you can use an ArrayList:
ArrayList list = new ArrayList();
list.Add("hello"); // OK
list.Add(123); // OK
But then you must know the type when you use an item from the list, since it can be any object.
I have a line of code like this:
List<string>[] apples = new List<string>()[2];
Its purpose is simply to create an array of List objects. When I try to compile my code, the above line generates this error:
Cannot implicitly convert type 'string' to 'System.Collections.Generic.List[]
I haven't been able to find much on the subject of creating an array of List objects (actually only this thread), maybe because no search engines will search for brackets.
Is the only way to create a collection of Lists to put them in another list, like below?
List<List<string>> apples = new List<List<string>>(); //I've tried this and it works as expected
Thanks for any suggestions, I'm really just curious as to why the first line of code (the List[] example) doesn't work.
You can do this. The syntax would be:
List<string>[] apples = new List<string>[2];
Note that this only allocates an array of references - you'll need to actually construct the individual list elements before you use them:
List<string>[] apples = new List<string>[2];
apples[0] = new List<string>();
apples[1] = new List<string>();
Alternatively, you can use the collection initialization syntax (works well for small numbers of fixed elements), ie:
List<string>[] apples = new[] { new List<string>(), new List<string>() };
Try this:
List<string>[] apples = new List<string>[2];
You do the initialization of each list afterwards:
apples[0] = new List<string>();
var listArray = new List<string>[2];
for (var i = 0; i < listArray.Length; i++)
{
listArray[i] = new List<string>();
}
I'm trying to do this:
var collection1 = new Collection<string> {"one", "two"};
var collection2 = new Collection<string> {"three", "four"};
var result = collection1.Concat(collection2);
But the result variable is type Enumerable[System.String]
, whereas I want a Collection[System.String]
I've tried casting:
var all = (Collection<string>) collection1.Concat(collection2);
But no joy.
var result = new Collection<string>(collection1.Concat(collection2).ToList());
For some reason System.Collections.ObjectModel.Collection requires an IList parameter to it's constructor. (The other collections only need an IEnumerator)
Use Enumerable.ToList(), as List<> is an ICollection<>.
E.g.:
IList list = a.Concat(b).ToList()
If you meant System.ObjectModel.Collection<> then you will have to pass the created list into the constructor of Collection<>, not ideal I know.
var collection = new System.ObjectModel.Collection<string>(a.Concat(b).ToList());