C# 6 - Index Initializers
نویسنده: وحید محمدطاهری
تاریخ: ۱۳۹۴/۰۷/۲۱ ۱۰:۳۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
enum USState {...}
var AreaCodeUSState = new Dictionary<string, USState>
{
{"408", USState.California},
{"701", USState.NorthDakota},
...
}; enum USState {...}
var AreaCodeUSState = new Dictionary<string, USState>
{
["408"] = USState.California,
["701"] = USState.NorthDakota,
...
}; create a Dictionary<string, USState>
add to new Dictionary the following items:
"408", USState.California
"701", USState.NorthDakota create a Dictionary<string, USState> then
using AreaCodeUSState's default Indexed property
set the Value of Key "408" to USState.California
set the Value of Key "701" to USState.NorthDakota enum USState {...}
var AreaCodeUSState = new Dictionary<string, USState>
{
{ "408", USState.Confusion},
{ "701", USState.NorthDakota },
{ "408", USState.California},
...
};
Console.WriteLine( AreaCodeUSState.Where(x => x.Key == "408").FirstOrDefault().Value ); enum USState {...}
var AreaCodeUSState = new Dictionary<string, USState>
{
["408"] = USState.Confusion,
["701"] = USState.NorthDakota,
["408"] = USState.California,
...
};
Console.WriteLine( AreaCodeUSState2.Where(x => x.Key == "408").FirstOrDefault().Value ); // output = California var fibonaccis = new List<int>
{
[0] = 1,
[1] = 2,
[3] = 5,
[5] = 13
} var fibonaccis = new List<int>()
{
1,
3,
5,
13
}; var countdown = new int[10]; // Initialize the array first countdown[^1] = 0; //last value countdown[^2] = 1; //second last value countdown[^3] = 2; countdown[^4] = 3; countdown[^5] = 4; countdown[^6] = 5; countdown[^7] = 6; countdown[^8] = 7; countdown[^9] = 8; countdown[^10] = 9; //first value
class Greeter
{
public char[] Message { get; set; } = "Hello?".ToCharArray();
public int[] SomeNums = new int[5];
public override string ToString()
{
return $"Message = {string.Join(',', Message)}, SomeNums = {string.Join(',', SomeNums)}";
}
}
var greeter = new Greeter {
Message = {
[^1] = '!'
},
SomeNums =
{
[^1] = 5,
[^2] = 4,
[^3] = 3,
[^4] = 2,
[^5] = 1
}
};Console.WriteLine(greeter);
Message = H,e,l,l,o,!, SomeNums = 1,2,3,4,5
var initialList = Enumerable.Range(1, 10);
var list = new List<int>(initialList)
{
[^1] = 15
};
Console.WriteLine(string.Join(" ", anotherList));
// 1 2 3 4 5 6 7 8 9 15