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.
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.
I have some code that moves variables around within a list, and I would like to write the name of a variable based on where it is located within the list.
This is what I tried:
int var1 = 4;
int var2 = 6;
int var3 = 12;
List<int> List = new List<int>() { var1, var2, var3 };
Console.WriteLine(nameof(List[1]));
I cannot (or at least I don't think I can) just write Console.WriteLine(nameof(var2)); because that will write var2 every time, but I want to be able to write the name of the second variable, even if I move the
location of each variable around.
Any help would be greatly appreciated :)
List does not store the actual variable, just the value of it. If you are wanting to store names and values, you'll want to use a dictionary or a list of KeyValuePairs instead, setting the 'name' to be the key and the value as the value.
Oakley is right. But I love dictionary in that case, because it's pretty simple and good in performance. Just check out the code.
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("var1", 4);
dictionary.Add("var2", 6);
dictionary.Add("var3", 12);
foreach (var i in dictionary)
{
System.Console.WriteLine(i.Key);
}
If you want that Key and Value could be any data type. Then you can use the following.
Dictionary<object, object> dictionary = new Dictionary<object, object>();
Another approach would be to simply create your own CLASS to hold the two values and make a List of that instead:
public class Data
{
public String Name;
public int Value;
}
public static void Main(string[] args)
{
List<Data> data = new List<Data>();
data.Add(new Data { Name = "var1", Value = 4 });
data.Add(new Data { Name = "var2", Value = 6 });
data.Add(new Data { Name = "var3", Value = 12 });
Console.WriteLine("1: " + data[1].Name);
data.Insert(1, new Data { Name = "newVar", Value = 5 });
Console.WriteLine("1: " + data[1].Name);
Console.WriteLine("2: " + data[2].Name);
Console.WriteLine("Press Enter to Quit");
Console.ReadLine();
}
public Class Elements
{
public string Name{get; set;}
public int ID {get; set;}
}
static main void ()
{
var element1 = new Elements(){ Name = var1, ID= 4};
var element2 = new Elements(){ Name = var2, ID= 6};
var element3 = new Elements(){ Name = var3, ID= 12};
var list = new List<Elements>() { element1, element2, element3 };
foreach(var e in list)
{
Console.WriteLine(e.Name);
}
}
Is there a List<> similar to a two dimension array? For each entry there is a number and text.
You can use Dictionary<int,String>
Sample:
Dictionary<int,string> samp = new Dictionary<int,string>();
dictionary.Add(1, "text1");
dictionary.Add(2, "text2");
Or, have a custom class which defines your requirement
public class Sample
{
public int Number;
public string Text;
}
Sample:
List<Sample> req = new List<Sample>();
Sample samObj = new Sample();
samObj.Number = 1;
samObj.Text = "FirstText";
req.Add(samObj);
There are many options, I describe some of them for you
use Dictionary<int, string>
Pros: very fast lookup
Cons: you can not have two string with same number, you don't have a List
var list2d = new Dictionary<int, string>();
list2d[1] = "hello";
list2d[2] = "world!";
foreach (var item in list2d)
{
Console.WriteLine(string.Format("{0}: {1}", item.Key, item.Value);
}
use Tuple<int, string>
Pros: very simple and handy tool, you have a List
Cons: Tuples are immutable, you can not change their values once you create them, reduces code readability (Item1, Item2)
var list2d = new List<Tuple<int, string>>();
list2d.Add(new Tuple(1, "hello"));
list2d.Add(Tuple.Create(1, "world");
foreach (var item in list2d)
{
Console.WriteLine(string.Format("{0}: {1}", item.Item1, item.Item2);
}
use a defined class,
Pros: you have a List, very customizable
Cons: you should write more code to setup
public class MyClass
{
public int Number { get; set; }
public string Text { get; set; }
}
var list2d = new List<MyClass>();
list2d.Add(new MyClass() { Number = 1, Text = "hello" });
list2d.Add(new MyClass { Number = 2, Text = "world" });
foreach (var item in list2d)
{
Console.WriteLine(string.Format("{0}: {1}", item.Number, item.Text);
}
Custom class or dictionary are good options, you can also use the Tuple generic...
var i = new List<Tuple<int, string>>();
Dictionary requires that whatever value is used as key must be unique. So not ideal without uniqueness.
A custom class is preferable if you don't mind a little more code and gives you scope to extend later on if you decide you want other data in there.
Tuple is quick and easy but you lose readability and objects can not be edited.
Define a class wih a string and an int property
public class MyClass
{
public string MyStr {get;set;}
public int MyInt {get;set;}
}
then create a list of this class
List<Myclass> myList = new List<MyClass>();
myList.add(new MyClass{MyStr = "this is a string", MyInt=5});
Hope it will help
public class DATA
{
public int number;
public string text;
}
List<DATA> list = new List<DATA>();
How can I store data from 2 columns (from a database) in a List
List<string> _items = new List<string>();
Any help is appreciated
You create a class that will represent a row with 2 columns:
public class Foo
{
// obviously you find meaningful names of the 2 properties
public string Column1 { get; set; }
public string Column2 { get; set; }
}
and then you store in a List<Foo>:
List<Foo> _items = new List<Foo>();
_items.Add(new Foo { Column1 = "bar", Column2 = "baz" });
Use a tuple struct like KeyValuePair
List<KeyValuePair<string, string>> _items = new List<KeyValuePair<string, string>>();
_items.Add(new KeyValuePair<string, string>(foo, bar));
I would use a class
List<MyDataClass> _items = new List<MyDataClass>();
public class MyDataClass
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
You can either create a new class to hold the data, Or you could use the built in Tuple<> class. http://msdn.microsoft.com/en-us/library/system.tuple.aspx
Also if one of the columns contains a unique ID of some sort, you could also consider using a Dictionary<>.
It's about how to retrieve the data from the new two columns list
List<ListTwoColumns> JobIDAndJobName = new List<ListTwoColumns>();
for (int index = 0; index < JobIDAndJobName.Count;index++)
{
ListTwoColumns List = JobIDAndJobName[index];
if (List.Text == this.cbJob.Text)
{
JobID = List.ID;
}
}
I know this question is pretty old and by now you probably got your answer and have figured out what you need but I wanted to add something that might help someone in the future.
The best current answer is frankly from #csharptest.net but it has a serious performance drawback and so here is my approach a la his answer based on a suggestion to use Dictionary<TKey, TValue>
private Dictionary<string, string> _items = new Dictionary<string, string>();
// if you need to check to see if it exists already or not
private void AddToList(string one, string two)
{
if (!_items.ContainsKey(one))
_items.Add(one, two);
}
// you can simplify the add further
private void AddToList(string one, string two)
{
_items[one] = two;
// note if you try to add and it exists, it will throw exception,
// so alternatively you can wrap it in try/catch - dealer's choice
}
you can also make array of list
List<string> [] list= new List<String> [];
list[0]=new List<string>();
list[1]=new List<string>();
list[0].add("hello");
list[1].add("world");
You could do this:
List<IList<string>> cols = new List<IList<string>>();
You can set how many columns you want.
cols.Add(new List<string> { "", "", "","more","more","more","more","..." });
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" }
};