List<string> icons = new List<string>[]
{
"!","!","N","N",",",",","k","k",
"b","b","v","v","w","w","z","z"
}
If i try to use code from above, compiler throws a message Error "; expected",
also if i add ";" at the end of the braces everything looks fine until i try to compile the program, then i get Error for each character in the list:
"Cannot implicitly convert type 'string' to 'System.Collections.Generic.List'"
And also another error that looks like this:
"Error 17 Cannot implicitly convert type 'System.Collections.Generic.List[]' to 'System.Collections.Generic.List'"
I need to mention that i use visual studio 2005, and I'm thinking perhaps this could be a reason why list doesn't works, since it worked for me in the newer version of visual studio 2015.
I am aware that List should look something like one from below, but if i try to use this syntax i get even more errors, and it looks like whole code is getting messed up.
List<string> icons = new List<string>()
{
"!","!","N","N",",",",","k","k",
"b","b","v","v","w","w","z","z"
}
Your second syntax is correct for C# 3.0 and later (though missing the final ;). See this fiddle for a demo.
List<string> icons = new List<string>()
{
"!","!","N","N",",",",","k","k",
"b","b","v","v","w","w","z","z"
};
Note that the () when using a collection initialiser { ... } is optional, so this could be written as:
List<string> icons = new List<string>
{
"!","!","N","N",",",",","k","k",
"b","b","v","v","w","w","z","z"
};
Your first attempt uses [], which attempts to initialise an array of List<string>. Each item in the initialiser (e.g. "!") would then be expected to be a List<string>. This isn't what you intended.
However, you state you are using Visual Studio 2005, which shipped with the C# 2.0 compiler. As this syntax was introduced in C# 3.0, so you won't be able to use it. You should ideally upgrade to a later version. The C# 2.0 equivalent syntax would be:
List<string> icons = new List<string>();
icons.Add("!");
icons.Add("!");
icons.Add("N");
// ...
The correct way is:
List<string> icons = new List<string>()
{
"!","!","N","N",",",",","k","k",
"b","b","v","v","w","w","z","z"
};
var icons = new List<string>()
{
"!","!","N","N",",",",","k","k",
"b","b","v","v","w","w","z","z"
};
You have to complete the statement with the semicolon (;) at the end
List<string> icons = new List<string>()
{
"!","!","N","N",",",",","k","k",
"b","b","v","v","w","w","z","z"
};
You're missing a ;. You should not put ; at the end of new List<string>() in case you want to use the intializer list syntax:
List<string> icons = new List<string>()
{
"!","!","N","N",",",",","k","k",
"b","b","v","v","w","w","z","z"
};
A statement can consist of a single line of code that ends in a
semicolon, or a series of single-line statements in a block. A
statement block is enclosed in {} brackets and can contain nested
blocks
Collection initializers
Collection initializers let you specify one or more element
initializers when you initialize a collection class that implements
IEnumerable or a class with an Add extension method. The element
initializers can be a simple value, an expression or an object
initializer. By using a collection initializer you do not have to
specify multiple calls to the Add method of the class in your source
code; the compiler adds the calls.
The following examples shows two simple collection initializers:
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
For C# 2.0 use this:
List<string> strings = new List<string>(new string[] { "1", "2", "3" });
You need a ; after closing }
List<string> icons = new List<string>()
{
"!","!","N","N",",",",","k","k",
"b","b","v","v","w","w","z","z"
};
and make sure you using
using System.Collections.Generic;
Related
I've just noticed that when you declare a List in c# you can put parentheses or curly braces at the end.
List<string> myList = new List<string>();
List<string> myList2 = new List<string>{};
Both these list appear to have the same functionality. Is there any actual difference caused by declaring them with parentheses or curly braces?
The use of curly braces { } is called a collection initializer. For types that implement IEnumerable the Add method would be invoked normally, on your behalf:
List<string> myList2 = new List<string>() { "one", "two", "three" };
Empty collection initializers are allowed:
List<string> myList2 = new List<string>() { };
And, when implementing an initializer, you may omit the parenthesis () for the default constructor:
List<string> myList2 = new List<string> { };
You can do something similar for class properties, but then it's called an object initializer.
var person = new Person
{
Name = "Alice",
Age = 25
};
And its possible to combine these:
var people = new List<Person>
{
new Person
{
Name = "Alice",
Age = 25
},
new Person
{
Name = "Bob"
}
};
This language feature introduced in C# 3.0 also supports initializing anonymous types, which is especially useful in LINQ query expressions:
var person = new { Name = "Alice" };
They also work with arrays, but you can further omit the type which is inferred from the first element:
var myArray = new [] { "one", "two", "three" };
And initializing multi-dimensional arrays goes something like this:
var myArray = new string [,] { { "a1", "b1" }, { "a2", "b2" }, ... };
Update
Since C# 6.0, you can also use an index initializer. Here's an example of that:
var myDictionary = new Dictionary<string, int>
{
["one"] = 1,
["two"] = 2,
["three"] = 3
};
They have different semantics.
List<string> myList = new List<string>();
The above line initializes a new List of Strings, and the () is part of the syntax of building a new object by calling its constructor with no parameters.
List<string> myList2 = new List<string>{};
The above line initializes a new List of Strings with the elements presented inside the {}. So, if you did List<string> myList2 = new List<string>{"elem1", "elem2"}; you are defining a new list with 2 elements. As you defined no elements inside the {}, it will create an empty list.
But why does the second line have no () ?
That makes part of a discussion in which omitting the parenthesis in this case represents a call to the default constructor. Take a look at This Link
The first version initialises an empty list. The second version is used to initialise the list with values. You wouldn't, or shouldn't, see the second version used without at least one instance of T.
So you could do something like:
List<string> Foo = new List<string>{"foo", "bar"};
or
List<T> Foo = new List<T>{SomeInstancesOfT};
This is useful in many places when initialising objects.
See https://msdn.microsoft.com/en-us/library/bb384062.aspx
To be short - there is no difference in the objects created.
But there's more:
What you are asking isn't a List specific question - it's a question of object and Collection initialization.
See here.
So, I'm working with c# and I'm trying to create a Bar graph in the console using strings. So I created a 2D list and gave each slot a default "empty" image.
List<List<string>> chart = new List<List<string>>() {"| |"};
but when i wrote it out, i got these two error messages in Visual studios
Error 1 Argument 1: cannot convert from 'string' to 'System.Collections.Generic.List<string>'
Error 2 The best overloaded Add method 'System.Collections.Generic.List<System.Collections.Generic.List<string>>.Add(System.Collections.Generic.List<string>)' for the collection initializer has some invalid arguments
The right syntax is
List<List<string>> chart = new List<List<string>>() { new List<String>() { "| |" }};
since you're creating list of list of string (2D list as you've put it), not just list of string.
When u need to create default string in your List try this:
List<string> chart = new List<string>() {"| |"};
or if u need initialize default string in your List of List<string> try
List<List<string>> chart = new List<List<string>>() { new List<string> { "| |" } };
You need to add List as parameter
List<List<string>> chart = new List<List<string>>() { new List<string>{"| |","| |"}};
I am new to the NDesk.Options library. Can't figure out the simplest way to parse a simple list of items.
Example:
prog --items=item1 item2 item3
(I want to use a List items in the code)
It should support quoting as well as I want to use the item list as list of file or dir names.
prog --items="c:\a\b\c.txt" "c:\prog files\d.txt"
prog --dirs="c:\prog files\" "d:\x\y\space in dirname"
You can use the "<>" input which denotes that no flag was associated with the input. Since the options are read left-to-right, you can set a 'currentParameter' flag when the starting flag is encountered, and assume any subsequent inputs without a flag are part of the list. Here is an example where we can specify a List as the input Files, and a Dictionary (Parameters) which are a list of key-value pairs. Other variations are of course available as well.
OptionSet options = new OptionSet()
{
{"f|file", "a list of files" , v => {
currentParameter = "f";
}},
{"p", #"Parameter values to use for variable resolution in the xml - use the form 'Name=Value'. a ':' or ';' may be used in place of the equals sign", v => {
currentParameter = "p";
}},
{ "<>", v => {
switch(currentParameter) {
case "p":
string[] items = v.Split(new[]{'=', ':', ';'}, 2);
Parameters.Add(items[0], items[1]);
break;
case "f":
Files.Add(Path.Combine(Environment.CurrentDirectory, v));
break;
}
}}
};
options.Parse(args);
An alternative to accept a list of values for a single argument is to accept the same argument multiple times. For example,
prog --file="c:\a\b\c.txt" --file="c:\prog files\d.txt"
In which case, your code would look something like this.
List<string> fileList = new List<string>();
OptionSet options = new OptionSet
{
{ "f|file", "File name. Repeat argument for each file.", v =>
{
fileList.Add(v);
}
}
};
options.Parse(args);
IMHO, this code is easier to read and maintain.
I have a bunch of string data and I can loop through it one by one. What's a good collection (and how to implement it) so that I only get the distinct strings?
The client I am doing this for doesn't even use .NET 3.5 so .Distinct is out. They use .NET framework 2.0.
And I am reading the list one at a time and don't know how many records it will have until I'm done.
One way is using Distinct to make your strings unique:
List<string> a = new List<string>();
a.AddRange(new string[] { "a", "b", "a", "c", "d", "b" });
List<string> b = new List<string>();
b.AddRange(a.Distinct());
Another resource on LINQ's Distinct: http://blogs.msdn.com/b/charlie/archive/2006/11/19/linq-farm-group-and-distinct.aspx
Another way: use a HashSet as others suggested;
HashSet<string> hash = new HashSet<string>(inputStrings);
Have a look for this link, to see how to implement it in .net 2.0: https://stackoverflow.com/a/687042/284240
If you're not on 3.5, you also can do it manually:
List<string> newList = new List<string>();
foreach (string s in list)
{
if (!newList.Contains(s))
newList.Add(s);
}
// newList contains the unique values
Another solution (maybe a little faster):
Dictionary<string,bool> dic = new Dictionary<string,bool>();
foreach (string s in list)
{
dic[s] = true;
}
List<string> newList = new List<string>(dic.Keys);
// newList contains the unique values
https://stackoverflow.com/a/1205813/284240
If you're using .Net 3.5 or above, put the strings in a List<> and use the linq method Distinct().
using System.Linq;
IEnumerable<string> strs = new List<string>(new[] { "one", "two", "three", "one" });
var distinct = strs.Distinct();
In .Net 2.0 you have no choice but to do it manually.
Perhaps I'm being dense and not fully understanding the question but can't you just use a regular List and just use the .Contains method to check if each string exists in the list before adding it in the loop? You might need to keep an eye on performance if you have a lot of strings.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Inline property initialisation and trailing comma
Working on one of my projects (C# 4.0, Visual Studio 2010), I've accidentally discovered that code like
var obj = new { field1 = "Test", field2 = 3, }
is compiled and executed OK without any errors or even warnings and works exactly like
var obj = new { field1 = "Test", field2 = 3 }
Why does compiler tolerate the trailing coma in first example? Is this a bug in compiler or such behavior does have some purpose?
Thanks
To determine whether or not it's a bug in the compiler, you need to look at the C# spec - in this case section 7.6.10.6, which clearly allows it:
anonymous-object-creation-expression:
new anonymous-object-initializer
anonymous-object-initializer:
{ member-declarator-listopt }
{ member-declarator-list , }
So no, it's not a compiler bug. The language was deliberately designed to allow it.
Now as for why the language has been designed that way - I believe it's to make it easier to add and remove values when coding. For example:
var obj = new {
field1 = "test",
field2 = 3,
};
can become
var obj = new {
field2 = 3,
};
or
var obj = new {
field1 = "test",
field2 = 3,
field3 = 4,
};
solely by adding or removing a line. This makes it simpler to maintain code, and also easier to write code generators.
Note that this is consistent with array initializers, collection initializers and enums:
// These are all valid
string[] array = { "hello", };
List<string> list = new List<string> { "hello", };
enum Foo { Bar, }
One reason the trailing commas is good is because of Source Compares. If you update the source and use a source compare tool, then the source compare tool will only show 1 line changed (the new field3. If there was no trailing comma, then source compare will show 2 lines changed because you had to add the comma after the number 3.
var obj = new {
field1 = "Test",
field2 = 3,
}
var obj = new {
field1 = "Test",
field2 = 3,
field3 = "New",
}
To make deleting the last field easier, I suppose. There is really no ambiguity introduced in the syntax by doing this, so it just makes life a bit easier.