Create list imperatively - c#

My goal is to create a imperative program in C# and I know how to go about just using a for loop or while loop etc. But I was told they way I'm using my data/getting the data which is not imperative? I want to have something like a list of lists? and doing so this way:
static void Main()
{
List<string> list1 = new List<string> {"asd","asfasf","asfasf"};
List<string> list2 = new List<string> {"asd","asfasf","asfasf"};
List<string> list3 = new List<string> {"asd","asfasf","asfasf"};
List<string> list4 = new List<string> {"asd","asfasf","asfasf"};
List<string> list5 = new List<string> {"asd","asfasf","asfasf"};
List<List<string>> lists = new List<List<string>> {list1,list2,list3,list4,list5};
}
I am not sure if this is an imperative approach to doing so or not?
I had this before which i know is basically the exact same:
static void Main()
{
List<List<string>> lists = new List<List<string>>();
lists.Add(new List<string> {"asd","asfasf","asfasf"});
}
But was told it wasn't as it was using parametric polymorphism which is OOP. I was told for likes of python and that that we couldn't use Lists unless we write our own list declaration and functioned. We also couldn't use built-in functions(e.g .split())

Related

How to convert List<object> to List of something else at runtime?

I have two lists.
List<string> listString;
List<int> listInt;
The input I get in is
List<object>
At runtime, is there a way to convert
List<object>
to another List?
Edit:
My question is how do I it at runtime. Not compile time.
List<string> listString = listObject.Cast<string>().ToList();
List<int> listInt = listObject.Cast<int>().ToList();
Try using the .OfType() filter to get the specific lists.
var all = new List<object>();
// add stuff
List<string> text = all.OfType<string>().ToList();
List<int> vals = all.OfType<int>().ToList();

How can I add an item to a list and return a new list

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();

initialising multiple empty lists

Simple syntactic c# question is this.
Given this code:
List<string> Columns = new List<string>();
List<string> Parameters = new List<string>();
List<string> Values = new List<string>();
It can be reduced to:
List<string> Columns = new List<string>(), Parameters = new List<string>(), Values = new List<string>();
But can I get it shorter still, since they're all being initialised to an empty list?
Thank you all!
I can recommend to use var keyword if these variables are not class fields, because types are know from usage. It really makes no sense to flat declaration of three variables.
var Columns = new List<string>();
var Parameters = new List<string>();
var Values = new List<string>();
Yes, you can do things, like declaring multiple local variables in one line and then initializing them in one line. But please, avoid declaring multiple variables in one line - it makes code much readable.
Purely as a point of trivia/code golf:
Func<List<string>> n = () => new List<string>();
List<string> a = n(), b = n(), c = n(), d = n(), e = n(), f = n();
But it would be ridiculous to use this in place of the much clearer constructs available. It might have value if the initialization was more complex, and the code was properly named and spaced.
Func<List<string>> setupFoo = () => {
return new List<string>() { 1, 2, 3 };
};
var option1 = setupFoo();
var option2 = setupFoo();
var option3 = setupFoo();
You can't shorten anymore.
You could use some kind of "empty list factory":
public static List<string> EmptySList()
{
return EmptyList<string>();
}
public static List<T> EmptyList<T>()
{
return new List<T>();
}
...
List<string> Columns = EmptySList(), Parameters = EmptySList(), Values = EmptySList();
Honestly, you probably don't want to shorten your code. Just write something readable and maintainable:
var columns = new List<string>();
var parameters = new List<string>();
var values = new List<string>();
This is not a great practice, but if you're initializing string lists a lot within a single .cs file, you can add an alias for the class with the file's other using statements:
using StringList = List<string>;
And then the code to declare and initialize them would be:
StringList Columns = new StringList(),
Parameters = new StringList(),
Values = new StringList();
IEnumerable is the most basic interface for collections. Using this, you can instantiate any type of collection dynamically.
For empty lists, use.
Enumerable.Empty<TYPE>();
In your example...
using using System.Collections.Generic;
...
IEnumerable<string> Columns = Enumerable.Empty<string>();
IEnumerable<string> Parameters = Enumerable.Empty<string>();
IEnumerable<string> Values = Enumerable.Empty<string>();

Difference between List<string> lst = new List() and List<> lst = new List()

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.

Can't create an array of list objects

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>();
}

Categories

Resources