I'm looking for a quick way to create a list of values in C#. In Java I frequently use the snippet below:
List<String> l = Arrays.asList("test1","test2","test3");
Is there any equivalent in C# apart from the obvious one below?
IList<string> l = new List<string>(new string[] {"test1","test2","test3"});
Check out C# 3.0's Collection Initializers.
var list = new List<string> { "test1", "test2", "test3" };
If you're looking to reduce clutter, consider
var lst = new List<string> { "foo", "bar" };
This uses two features of C# 3.0: type inference (the var keyword) and the collection initializer for lists.
Alternatively, if you can make do with an array, this is even shorter (by a small amount):
var arr = new [] { "foo", "bar" };
In C# 3, you can do:
IList<string> l = new List<string> { "test1", "test2", "test3" };
This uses the new collection initializer syntax in C# 3.
In C# 2, I would just use your second option.
IList<string> list = new List<string> {"test1", "test2", "test3"}
You can do that with
var list = new List<string>{ "foo", "bar" };
Here are some other common instantiations of other common Data Structures:
Dictionary
var dictionary = new Dictionary<string, string>
{
{ "texas", "TX" },
{ "utah", "UT" },
{ "florida", "FL" }
};
Array list
var array = new string[] { "foo", "bar" };
Queue
var queque = new Queue<int>(new[] { 1, 2, 3 });
Stack
var queque = new Stack<int>(new[] { 1, 2, 3 });
As you can see for the majority of cases it is merely adding the values in curly braces, or instantiating a new array followed by curly braces and values.
You can drop the new string[] part:
List<string> values = new List<string> { "one", "two", "three" };
You can simplify that line of code slightly in C# by using a collection initialiser.
var lst = new List<string> {"test1","test2","test3"};
You can just:
var list = new List<string> { "red", "green", "blue" };
or
List<string> list = new List<string> { "red", "green", "blue" };
Checkout: Object and Collection Initializers (C# Programming Guide)
You can create helper generic, static method to create list:
internal static class List
{
public static List<T> Of<T>(params T[] args)
{
return new List<T>(args);
}
}
And then usage is very compact:
List.Of("test1", "test2", "test3")
If you want to create a typed list with values, here's the syntax.
Assuming a class of Student like
public class Student {
public int StudentID { get; set; }
public string StudentName { get; set; }
}
You can make a list like this:
IList<Student> studentList = new List<Student>() {
new Student(){ StudentID=1, StudentName="Bill"},
new Student(){ StudentID=2, StudentName="Steve"},
new Student(){ StudentID=3, StudentName="Ram"},
new Student(){ StudentID=1, StudentName="Moin"}
};
If we assume there is a class named Country , than we can do like this:
var countries = new List<Country>
{
new Country { Id=1, Name="Germany", Code="De" },
new Country { Id=2, Name="France", Code="Fr" }
};
Related
I am creating a dictionary in a C# file with the following code:
private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT
= new Dictionary<string, XlFileFormat>
{
{"csv", XlFileFormat.xlCSV},
{"html", XlFileFormat.xlHtml}
};
There is a red line under new with the error:
Feature 'collection initilializer' cannot be used because it is not part of the ISO-2 C# language specification
What is going on here?
I am using .NET version 2.
I can't reproduce this issue in a simple .NET 4.0 console application:
static class Program
{
static void Main(string[] args)
{
var myDict = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
Console.ReadKey();
}
}
Can you try to reproduce it in a simple Console application and go from there? It seems likely that you're targeting .NET 2.0 (which doesn't support it) or client profile framework, rather than a version of .NET that supports initialization syntax.
With C# 6.0, you can create a dictionary in the following way:
var dict = new Dictionary<string, int>
{
["one"] = 1,
["two"] = 2,
["three"] = 3
};
It even works with custom types.
You can initialize a Dictionary (and other collections) inline. Each member is contained with braces:
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
{ 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
{ 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
{ 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};
See How to initialize a dictionary with a collection initializer (C# Programming Guide) for details.
Suppose we have a dictionary like this:
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");
We can initialize it as follows.
Dictionary<int, string> dict = new Dictionary<int, string>
{
{ 1, "Mohan" },
{ 2, "Kishor" },
{ 3, "Pankaj" },
{ 4, "Jeetu" }
};
Object initializers were introduced in C# 3.0. Check which framework version you are targeting.
Overview of C# 3.0
Note that C# 9 allows Target-typed new expressions so if your variable or a class member is not abstract class or interface type duplication can be avoided:
private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT = new ()
{
{ "csv", XlFileFormat.xlCSV },
{ "html", XlFileFormat.xlHtml }
};
With ะก# 6.0
var myDict = new Dictionary<string, string>
{
["Key1"] = "Value1",
["Key2"] = "Value2"
};
Here is an example of Dictionary with Dictionary value
Dictionary<string, Dictionary<int, string>> result = new() {
["success"] = new() {{1, "ok"} , { 2, "ok" } },
["fail"] = new() {{ 3, "some error" }, { 4, "some error 2" } },
};
which is equivalent to this in JSON :
{
"success": {
"1": "ok",
"2": "ok"
},
"fail": {
"3": "some error",
"4": "some error 4"
}
}
The code looks fine. Just try to change the .NET framework to v2.0 or later.
Have some List of Application object
Application has Property Status and it holds values {"Red",Yellow,Blue ,Green and Orange")
My Requirement is to sort List in custom sort order
"Red" Should come first
"Blue" Second
"Yellow" Third
"Green" last
How to implement Sorting in this scenario .
Please help .
Thanks in advance
Well, you could create a list of sorted values and then sort by index in it:
var sortedValues = new List<string> {"Red", "Blue", "Yellow", "Green", "Orange"};
var result = myList.OrderBy(a => sortedValues.IndexOf(a.Status));
Define a new class with Id and Name of color property.
Create an array of the class and order the array by Id.
class CutomSort
{
class Color
{
public int Id;
public string Name;
}
static void Main(string[] args)
{
Color[] input = {
new Color{Id=4, Name="Green"},
new Color{Id=3, Name="Yellow"},
new Color{ Id=1, Name="Red"},
new Color{ Id = 2, Name = "Blue" }
};
IEnumerable<Color> result = input.OrderBy(x => x.Id);
foreach (Color color in result)
{
Console.WriteLine($"{color.Id}-{color.Name}");
}
Console.ReadKey();
}
}
I've been using C# for a while, but recently noticed that the behaviour of one of my unit tests changed depending on which variation of collection initialiser expression I used:
var object = new Class { SomeCollection = new List<int> { 1, 2, 3 } };
var object = new Class { SomeCollection = { 1, 2, 3 } };
Up until this point I assumed that the second form was just syntactic sugar and was semantically equivalent to the first form. However, switching between these two forms resulted in my failing unit test passing.
The example code below demonstrates this:
void Main()
{
var foo1 = new Foo { Items = new List<int> { 1, 2, 3} };
var foo2 = new Foo { Items = { 1, 2, 3 } };
foo1.Dump();
foo2.Dump();
}
class Foo
{
public List<int> Items { get; set; }
}
When I run this, the first assignment works fine but the second results in a NullReferenceException.
My gut feeling is that behind the scenes the compiler is treating these two expressions as this:
var foo1 = new Foo();
foo1.Items = new List<int> { 1, 2, 3 };
var foo2 = new Foo();
foo2.Items.Add(1);
foo2.Items.Add(2);
foo2.Items.Add(3);
Is that assumption accurate?
Yes, your assumption is accurate. If an object initializer just has:
{
Property = { ... }
}
rather than
{
Property = expression
}
then the setter for the property isn't used - the getter is used, and then either the Add method is called, or properties are set within the returned value. So:
var foo = new Foo
{
Collection = { 1 }
Property =
{
Value = 1
}
};
is equivalent to:
// Only the *getters* for Collection and Property are called
var foo = new Foo();
foo.Collection.Add(1);
foo.Property.Value = 1;
Compare that with:
var foo = new Foo
{
Collection = new List<int> { 1 },
Property = new Bar { Value = 1 }
};
which is equivalent to:
// The setters for Collection and Property are called
var foo = new Foo();
foo.Collection = new List<int> { 1 };
foo.Property = new Bar { Value = 1 };
What is the easiest way to filter a value with a null reference checking.Order should be like "Active",
"Reset",
"Locked",
"Suspended ",
"Expired",
"Disabled ",
"Revoked"
namespace ConsoleApplication1
{
class Program
{
private static void Main(string[] args)
{
var tempList = new List<string>
{
"Active",
"Reset",
"Locked",
"Suspended ",
"Expired",
"Disabled ",
"Revoked"
};
var list = new List<MyEntity>
{
new MyEntity() {MyValue = "Reset"},
new MyEntity() {MyValue = "Locked"},
new MyEntity() {MyValue = "Active"},
new MyEntity() {MyValue = "Expired"}
};
var item =
list.FirstOrDefault(x => x.MyValue));
}
}
public class MyEntity
{
public string MyValue { get; set; }
}
}
What I need to do to get the filter the list based on value ...
It sounds like you want to do an OrderBy and if you want the preference to be Sam, then Paul, then Jimmy, then Jeff, and then null if none of those are present then you can do the following.
var listOfNames = new List<string> { "Sam", "Paul", "Jimmy", "Jeff" };
var item = list.Where(x => listOfNames.Contains(x.MyValue))
.OrderyBy(x => listOfName.IndexOf(x.MyValue))
.FirstOrDefault();
This will first filter out anything that doesn't match the values you are interested it. Then orders them by their position in the list and finally picks the first one or null if the filter resulted in no matches.
Also I'm just assuming MyValue is a string here, but if you need to you can do whatever conversion is needed.
I have two classes: consumableItems.cs and items.cs
So basically, all I have to do is inherit the properties of items.cs to consumableItems.cs
Here's what I done so far:
class Item
{
public List<string> itemNames = new List<string>();
public List<int> itemEffects = new List<int>();
}
class consumableItems : Item
{
new public List<string> itemNames = new List<string>() { "Apple", "Orange", "Grapes" };
new public List<int> itemEffects = new List<int>() { 15, 30, 40 };
}
What I want to achieve is, whenever I type "Apple", the console window shows both "Apple" and "15"; same for when I type "Orange", the console window shows both "Orange" and "30". Any ideas? Sorry, just started C# programming and I'm getting lost. >< Oh, and last question, is the way I inherit correct? :/ Thanks. ^^
If you just starting with C# what about changing from List to Dictionnary ?
a Dictionary would give you what you want.
With two lists, you have to loop over the first one to find the index and then access the second list with the index. Be careful with Exception in that case.
Regarding inheritance, you should check for (public|private|Etc...) and maybe look for Interfaces and Abstract
You are re-inventing the wheel and making life hard. Just use a dictionary:
var items = new Dictionary<string, int>
{
{ "Apple", 15 },
{ "Orange", 30 },
{ "Grapes", 40 }
};
Console.WriteLine("Apple = {0}", items["Apple"]);
I propose you to define a class
class Item {
public string Name { get; set;}
public int Effect { get; set;}
}
And then use a single List<Item> instead of trying to map between the two lists. You could override the ToString() method of the class for your Console output.
Use Dictionary like in example below:
class Program2
{
class ConsumableItems
{
new public List<string> itemNames = new List<string>() { "Apple", "Orange", "Grapes" };
new public List<int> itemEffects = new List<int>() { 15, 30, 40 };
public Dictionary<string, int> values = new Dictionary<string, int>()
{
{"Apple", 15},
{"Orange", 30},
{"Grapes", 40}
};
}
static void Main()
{
ConsumableItems items = new ConsumableItems();
string key = Console.ReadLine();
Console.WriteLine("\n\n\n");
Console.WriteLine(key + " " + items.values[key]);
Console.ReadKey();
}
}
You can use Dictionary instead of List ,
public Dictionary<string, int> FruitValues = new Dictionary<string, int>()
{
{"Apple", 15},
{"Orange", 30},
{"Grapes", 40}
};
Console.WriteLine("Apple Value is {0}", FruitValues["Apple"]);
Same business problem can easily be solved by using any collection of Key-Value pair.. I mean using dictionary like:
public Dictionary<string, int> FruitsEffect= new Dictionary<string, int>()
FruitsEffect.Add("FruitsName",25);
The Dictionary has pairs of keys and values.Dictionary is used with different elements. We specify its key type and its value type (string, int).
Populate the dictionary and get the value by key.