当前位置:网站首页>C custom set
C custom set
2022-07-27 11:29:00 【Hellfire Citadel 】
Main collection classes
Interface level interface structure


List collection :List<T>
Custom collection sorting
Each element can be accessed individually by index ,List<T> It's an ordered set , Calling the built-in method Sort() Then the elements will be reordered alphabetically .
If the element type implements generics IComparable<T> Or non generic interfaces IComparable By default, the sorting algorithm uses it to determine the sorting order .
If not , Or the default logic does not meet the requirements , You can call List<T>.Sort() The overloaded version of , He got one IComparaer<T> As an argument
IComparable<T> and IComparaer<T> The difference is that , The former Know how to compare myself with another instance of the same type , the latter Know how to compare two instances of a given type
When implementing sorting logic, ensure full order , Ensure that the permutation and combination of the same data will produce consistent results , For example, judgment is transitive , Equal to itself …
It is worth noting that , No element in the judgment can be null It returns equal , Otherwise, two non null Elements are equal to null But they are not equal to each other ,null Different values should be returned on the left and right sides of the identifier
Dictionaries :Dictionary<TKey,TValue>
var colorMap = new Dictionary<string, ConsoleColor>{
["Error"] = ConsoleColor.Red;
["Warning"] = ConsoleColor.Yellow;
}
// Two ways of inserting , The latter can also be used to change
colorMap.Add("Information", ConsoleColor.Green);
colorMap["Verbose"] = ConsoleColor.White;
//foreach Ergodic dictionary
private static void Print( IEnumerable<KeyValuePair<string, ConsoleColor>> items){
foreach(KeyValuePair<string, ConsoleColor> item in items){
Console.WriteLine(item.Key);
}
}
Again , The order of the elements in the dictionary is not certain , Don't rely on it
The dictionary is to determine whether it matches the existing key , If the dictionary value is customized , It is necessary to realize the judgment logic , In addition, we need to implement a return “ Hash code ” Methods to quickly index
Indexer
Array , Both dictionaries and lists provide indexers , You can define your own indexer
// Defines a set containing only two elements
public enum PairItem{
First,
Second
}
public struct Pair<T> {
public Pair(T first, Tsecond){
First = first;
Second = second;
}
public T First { get; }
public T Second { get; }
public T this[PairItem index]{
get{
switch(index){
case PairItem.First:
return First;
case PairItem.Second:
return Second;
default:
throw new NotImplementedException(
string.Format("The enum {0} has not been implemented"), index.ToString())
);
}
}
}
// It is very similar to the declaration of attributes , But use keywords this, Included later [ parameter list ], Can have multiple parameters
// If the set is empty , It's better not to go back null,
// Instead, it returns a collection instance that does not contain any data items , have access to Enumerable.Empty<T>() To generate
// This eliminates the need to check before traversing the collection elements null value
}
iterator
foreach loop
The first element is determined , The next element and the last element do not need to know the total number of elements
Look at this picture again ,IEnumerable The only way to do it is GetEnumerator() The function is to return support IEnumerator<T> An object of , It is equivalent to a bookmark to make the loop interleave through a set without interfering with each other .

foreach use while The equivalent code of is as follows
Stack<int> stack = new Stack<int>();
int number;
Stack<int>.Enumerator enumerator;
enumerator = stack.GetEnumerator();
while(enumerator.MoveNext()){
number = enumerator.Current;
Console.WriteLine(number);
}
From the code, we can also see why the compiler prohibits number Assign a value , Because it's only a local variable , It doesn't change the set element itself .
Iterators generate values
Iterators are similar to functions , But it is not the return value (return), Instead, generate values (yield).
Why? yield Add return Well , because C# Experts believe that adding a new keyword just for this situation is not enough , So will yield return Whole as a keyword ,yield Nothing happens when it appears alone .
Every time the iterator encounters yield return Will generate a value , Immediately return to the caller of the requested data item . Then when requesting the next item , Will be followed by the last yield return Execute after statement .
foreach Each cycle of is represented by a MoveNext Start , After generating a value, return it to foreach sentence . perform yield return after , GetEnumerator() Method pauses and waits for the next MoveNext()
If you need to cancel the iteration , Then yield break Immediately return control to the caller and terminate the loop
Query expression
C# For a set, you can filter the set through a query expression , And project the set . His grammar and SQL The language is as like as two peas.
static string[] Keywords = {"abstract", "add*", "alias", "async*"};
private static void ShowSpeacilWords{
IEnumerable<string> selection =
form word in Keywords
where !word.Contains('*')
select word;
foreach(string keyword in selection){
Console.Write(keyword + "");
}
}
and SQL The main difference between sentences is C# The sentence order of the query expression is from、where、select, and SQL The sentence is SELECT、FROM、WHERE
Besides, there are group by,order by Wait for a series of keywords
private static void GroupKeyword(){
IEnumerable<IGrouping<bool,string>> selection =
from word in Keyword
group word by word.Contains('*');
}
边栏推荐
- 高斯消元 AcWing 883. 高斯消元解线性方程组
- Find the combination number acwing 886. find the combination number II
- Digital triangle model acwing 275. pass note
- Game theory acwing 893. Set Nim game
- Yiwen counts NFT projects valued at more than US $100million
- Markdown editor syntax - setting of text color, size, font and background color (Reprint)
- 解决 ImportError: cannot import name 'abs' 导入tensorflow报错
- Properties file
- Smart pointer (shared_ptr, unique_ptr, weak_ptr)
- Knapsack model acwing 423. Picking herbs
猜你喜欢

15 design movie rental system

Gaussian elimination acwing 883. solving linear equations with Gaussian elimination

区间问题 AcWing 906. 区间分组

Knapsack problem acwing 9. grouping knapsack problem

状态压缩DP AcWing 91. 最短Hamilton路径

力扣——10. 正则表达式匹配

数字三角形模型 AcWing 1015. 摘花生

FAQs of "relay chain" and "dot" in Poka ecosystem

Where is the big data open source project, one-stop fully automated full life cycle operation and maintenance steward Chengying (background)?

Gaussian elimination acwing 884. Gaussian elimination for solving XOR linear equations
随机推荐
Wechat push - template message parameter configuration
2022 Niuke multi school training (3) a-ancestor topic translation
Cancer DDD
求组合数 AcWing 886. 求组合数 II
数字三角形模型 AcWing 1015. 摘花生
Remember an experience of using canvas to make the banner streamer effect of Tencent cloud homepage
Properties file
Error while unzipping file in win10: unable to create symbolic link. You may need to run WinRAR with administrator privileges. The client does not have the required privileges
博弈论 AcWing 891. Nim游戏
Luogu p1441 weight weighing
First experience of three.js: simulating the growth of a small branch
Longest ascending subsequence model acwing 1012. Sister Cities
Kepserver configuration
(8) Shell function
7 row K with the weakest combat effectiveness in the matrix
2022牛客多校训练(3)A-Ancestor 题目翻译
What is the issuing price of NFT (Interpretation of NFT and establishment of NFT world outlook)
Caused by:org.gradle.api.internal.plugins . PluginApplicationException: Failed to apply plugin
洛谷P1896 互不侵犯
WGet warning: unable to verify