Example 1: c# lists
using System.Collections.Generic
var myList = new List<int>();
List<int> myList = new List<int>();
List<int> myList = new List<int>() {2, 5, 9, 12};
string myString = "Hello"
List<char> myList = new List<char>(myString);
var myFirstList = new List<int>() {9, 2, 4, 3, 2, 1};
var mySecondList = new List<int>(myFirstList);
myList.Add(4);
myList.Insert(0,3)
myList.AddRange(new int[3] {3, 5, 5, 9, 2});
for (int i = 0; i < myList.Count; i++)
{
if ( myList[i] == 5)
{
myList.Remove(myList[i]);
i--;
}
}
myList.Clear();
List<List<int>> myList = new List<List<int>>(){
new List<int>() {1,2,3},
new List<int>() {4,5,6},
new List<int>() {7,8,9}
};
Console.WriteLine(myList.ElementAt(0).ElementAt(1));
Example 2: how to create a list c#
C# By Magnificent Mamba on Dec 23 2019
IList<int> newList = new List<int>(){1,2,3,4};
Example 3: c# get list object type of generic list
Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
== typeof(List<>))
{
Type itemType = type.GetGenericArguments()[0];
}
Example 4: c# list of different objects
Or is there a better/different way to do this?
If your objects descend from a common class, then you can store them in the same collection. In order to do anything useful with your objects without throwing away type safety, you'd need to implement the visitor pattern:
public interface EntityVisitor
{
void Visit(Arc arc);
void Visit(Line line);
}
public abstract class Entity
{
public abstract void Accept(EntityVisitor visitor);
}
public class Arc : Entity
{
protected double startx;
protected double starty;
protected double endx;
protected double endy;
protected double radius;
public override void Accept(EntityVisitor visitor)
{
visitor.Visit(this);
}
}
public class Line : Entity
{
protected double startx;
protected double starty;
protected double endx;
protected double endy;
protected double length;
public override void Accept(EntityVisitor visitor)
{
visitor.Visit(this);
}
}
Once that's in place, you create an instance of EntityVisitor whenever you need to do something useful with your list:
class EntityTypeCounter : EntityVisitor
{
public int TotalLines { get; private set; }
public int TotalArcs { get; private set; }
#region EntityVisitor Members
public void Visit(Arc arc) { TotalArcs++; }
public void Visit(Line line) { TotalLines++; }
#endregion
}
class Program
{
static void Main(string[] args)
{
Entity[] entities = new Entity[] { new Arc(), new Line(), new Arc(), new Arc(), new Line() };
EntityTypeCounter counter = entities.Aggregate(
new EntityTypeCounter(),
(acc, item) => { item.Accept(acc); return acc; });
Console.WriteLine("TotalLines: {0}", counter.TotalLines);
Console.WriteLine("TotalArcs: {0}", counter.TotalArcs);
}
}
And for what its worth, if your open to trying new languages, then F#'s tagged unions + pattern matching are a handy alternative to the visitor pattern.