معرفی List Patterns Matching در C# 11
نویسنده: وحید نصیری
تاریخ: ۱۴۰۱/۰۹/۰۱ ۱۲:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
[1, 2, .., 10]
int[] arr1 = { 1, 2, 10 };
int[] arr2 = { 1, 2, 5, 10 };
int[] arr3 = { 1, 2, 5, 6, 7, 8, 9, 10 }; int[] collection = { 1, 2, 3, 4 }; Console.WriteLine(collection is [1, 2, 3, 4]); // True Console.WriteLine(collection is [1, 2, 4]); // False
Console.WriteLine(collection is [_, 2, _, 4]); // True Console.WriteLine(collection is [.., 3, _]); // True
if (new[] { 6, 7, 8 } is [_, _, ..])
{
Console.WriteLine($"collection with at least two items");
} if (new[] { 0, 42, 42, 0 } is [0, .., 0])
{
Console.WriteLine($"collection with first and last element equal to 0");
} Console.WriteLine(collection is [_, >= 2, _, _]); // True
if (new[] { 9, -1, -2 } is [> 0, ..])
{
Console.WriteLine($"collection with positive first element");
} if (new[] { 1, 42, 0 } is [_, 42 or -42, ..])
{
Console.WriteLine($"collection with second element equal to 42 or -42");
} namespace CS11Tests;
public static class ListPatternsMatching
{
public static void Test()
{
Console.WriteLine(CheckSwitch(new[] { 1, 2, 10 })); // prints 1
Console.WriteLine(CheckSwitch(new[] { 1, 2, 7, 3, 3, 10 })); // prints 1
Console.WriteLine(CheckSwitch(new[] { 1, 2 })); // prints 2
Console.WriteLine(CheckSwitch(new[] { 1, 3 })); // prints 3
Console.WriteLine(CheckSwitch(new[] { 1, 3, 5 })); // prints 4
Console.WriteLine(CheckSwitch(new[] { 2, 5, 6, 7 })); // prints 50
}
public static int CheckSwitch(int[] values)
=> values switch
{
[1, 2, .., 10] => 1,
[1, 2] => 2,
[1, _] => 3,
[1, ..] => 4,
[..] => 50
};
} if (new[] { 1, 2, 3 } is [var first, _, _])
{
Console.WriteLine($"three item collection with first item {first}");
}
if (new[] { 4, 5, 6 } is [_, var second, _])
{
Console.WriteLine($"three item collection with second item {second}");
} var uri = new Uri("http://www.mysite.com/categories/category-a/sub-categories/sub-category-a.html");
var result = uri.Segments switch
{
["/"] => "Root",
[_, var single] => single,
[_, .. string[] entries, _] => string.Join(" > ", entries)
}; List<int> collection = new() { 1 };
var formattedItemBefore = collection.SingleOrDefault() is { } item
? $"Formatted: {item}"
: "No items found"; var formattedItemAfter = collection switch
{
[] => "No items found",
[var singleItem] => $"Formatted: {singleItem}",
_ => throw new InvalidOperationException($"Expected 0 or 1 items, but received {collection.Count} items.")
}; ReadOnlySpan<char> strSpan = "Vahid";
if (strSpan is "Vahid")
{
Console.WriteLine("Hey, Vahid");
} if (strSpan is ['V', ..])
{
Console.WriteLine("The name starts with V");
} var values = Enumerable.Range(start: 1, count: 10).ToArray(); // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Console.WriteLine($"MultiplyAll: {MultiplyAll(values)}"); // MultiplyAll: 3628800
Console.WriteLine($"AddAll: {AddAll(values)}"); // AddAll: 55
static int MultiplyAll(params int[] values) =>
values switch
{
[] => 1,
[var first, .. var rest] => first * MultiplyAll(rest)
};
static int AddAll(params int[] elements) =>
elements switch
{
[] => 0,
[var first, .. var rest] => first + AddAll(rest)
}; var data = "item1|item2|item3";
var collection = data.Split('|'); var formattedDataBefore = collection.Length switch
{
2 => FormatData(collection[0], collection[1]),
3 => FormatData(collection[0], collection[1], collection[2]),
var length => throw new InvalidOperationException($"Expected 3 parts, but got {length} parts for formatted string: {data}."),
}; var formattedDataAfter = collection switch
{
[var part1, var part2] => FormatData(part1, part2),
[var part1, var part2, var part3] => FormatData(part1, part2, part3),
var parts => throw new InvalidOperationException($"Expected 3 parts, but got {parts.Length} parts for formatted string: {data}."),
}; public class Song
{
public string Name { get; set; }
public List<string> Lyrics { get; set; }
} for (var i = 0; i < songs.Count; i++)
{
if (songs[i].Lyrics[0] == "Hello" && songs[i].Lyrics.Count == 6 &&
songs[i].Lyrics[songs[i].Lyrics.Count - 1] == "?")
{
Console.WriteLine($"{i}");
}
} for (var i = 0; i < songs.Count; i++)
{
if (songs[i].Lyrics is ["Hello", _, _, _, _, "?"])
{
Console.WriteLine($"{i}");
}
} foreach (Song song in songs)
{
if (song.Lyrics is ["Hello", .., "?"])
{
Console.WriteLine(song.Name);
}
} foreach (Song song in songs)
{
if (song.Lyrics is ["Hello", "from" or "is", var third, var forth, var fifth])
{
Console.WriteLine(song.Name);
Console.WriteLine($"The third word is : {third}");
Console.WriteLine($"The forth word is : {forth}");
Console.WriteLine($"The fifth word is : {fifth}");
}
} public int Length { get; }
public int Count { get; } public object this[int index] => throw null; public object this[System.Index index] => throw null;
public object this[System.Range index] => throw null; public object Slice(int start, int length) => throw null;
public class MyListPatternsCompatibleCollection
{
private readonly List<int> _items = new();
public int Length => _items.Count;
public int this[Index index] => _items[index];
public ReadOnlySpan<int> this[Range range]
=> CollectionsMarshal.AsSpan(_items)[range];
public void Add(int item) => _items.Add(item);
} var collection = new MyListPatternsCompatibleCollection(); collection.Add(1); collection.Add(2); collection.Add(3); _ = collection is [var head, .. var tail];