当前位置:网站首页>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('*');
}
边栏推荐
- Lazy loading of lists and pictures
- 【着色器实现Shake随机摇动效果_Shader效果第十篇】
- Digital triangle model acwing 1015. Picking flowers
- Today's code farmer girl summarized her notes about NPM package management and URL module
- 求组合数 AcWing 886. 求组合数 II
- Knapsack model acwing 1024. Packing problem
- Chinese remainder theorem acwing 204. strange way of expressing integers
- 最长上升子序列模型 AcWing 1017. 怪盗基德的滑翔翼
- (5) Printf (instead of echo)
- 最长上升子序列模型 AcWing 1010. 拦截导弹
猜你喜欢

Find the combinatorial number acwing 889. 01 sequence satisfying the condition

Chinese remainder theorem acwing 204. strange way of expressing integers

Game theory acwing 891. Nim game

When std:: bind meets this

15 design movie rental system

为什么选择智能电视?

Gaussian elimination acwing 883. solving linear equations with Gaussian elimination

Tree DP acwing 285. dance without boss

The longest ascending subsequence model acwing 1016. The sum of the largest ascending subsequence

Find the combination number acwing 886. find the combination number II
随机推荐
Properties file
JVM judges that the object is dead, and practices verify GC recycling
Longest ascending subsequence model acwing 272. longest common ascending subsequence
Longest ascending subsequence model acwing 1010. Interceptor missile
ethereum rpc
最长上升子序列模型 AcWing 1016. 最大上升子序列和
Solve importerror: cannot import name'abs'import tensorflow error
区间问题 AcWing 906. 区间分组
2022 Niuke multi school training (3) a-ancestor topic translation
Description and feelings
9 UAV array
349两个数组的交集和01两数之和
2022牛客多校 (3)J.Journey
What is the mystery of the gate of the meta universe?
6 find the smallest letter larger than the target letter
What is private traffic?
求组合数 AcWing 888. 求组合数 IV
The longest ascending subsequence model acwing 1017. The glider wing of the strange thief Kidd
11 wrong set
Pat (Grade B) 2022 summer exam