C#.NET 利用ToDictionary(),GroupBy(),可以將List轉(zhuǎn)化為Dictionary,主需要一行代碼!
首先看一下需求,已知cars,等于:
List<Car> cars = new List<Car>(){ new Car(1,"audiA6","private"), new Car(2,"futon","merchant"), new Car(3,"feiren","bike"), new Car(4,"bukon","private"), new Car(5,"baoma","private"), new Car(6,"dayun","merchant") };
1)我想以id為鍵,值為Car轉(zhuǎn)化為一個字典idCarDict,方法如下:
var idCarDict = cars.ToDictionary(car=>car.id);
這樣保證能正確轉(zhuǎn)化的前提為,id在列表中沒有重復(fù)值。如果有重復(fù)的,會拋出向字典中添加重復(fù)值的異常。
2)我想以type為鍵,值car的List的typeDict,方法如下:
Dictionary<string, List<Car>> typeCarDict = cars.GroupBy(car => car.type).ToDictionary(r => r.Key, r => r.ToList());
分步解釋:
第一步分組
cars.GroupBy(car=>car.type) //返回的結(jié)果類型為: //IEnumerable<IGroup<string,car>>; //其中string等于car.type,也就是分組的鍵
第二步將IEnumerable類型轉(zhuǎn)化為字典,選取合適的鍵,
ToDictionary(r=>r.Key,r=>r.ToList());//r參數(shù)代表分組對象,r.Key便是car.type;//r.ToList()操作后將分組對象轉(zhuǎn)化為List對象
這種轉(zhuǎn)化代碼簡介,比以下foreach遍歷得到以car.type的字典簡潔許多:
var dict = new Dictionary<string,List<Car>>(); foreach(var car in cars) { if(dict.Contains(car.type)) dict[car.type].Add(car); else dict.Add(car.type,new List<Car>(){car}));}
C#.NET 利用ToDictionary(),GroupBy(),可以將List轉(zhuǎn)化為Dictionary,主需要一行代碼!
首先看一下需求,已知cars,等于:
List<Car> cars = new List<Car>(){ new Car(1,"audiA6","private"), new Car(2,"futon","merchant"), new Car(3,"feiren","bike"), new Car(4,"bukon","private"), new Car(5,"baoma","private"), new Car(6,"dayun","merchant") };
1)我想以id為鍵,值為Car轉(zhuǎn)化為一個字典idCarDict,方法如下:
var idCarDict = cars.ToDictionary(car=>car.id);
這樣保證能正確轉(zhuǎn)化的前提為,id在列表中沒有重復(fù)值。如果有重復(fù)的,會拋出向字典中添加重復(fù)值的異常。
2)我想以type為鍵,值car的List的typeDict,方法如下:
Dictionary<string, List<Car>> typeCarDict = cars.GroupBy(car => car.type).ToDictionary(r => r.Key, r => r.ToList());
分步解釋:
第一步分組
cars.GroupBy(car=>car.type) //返回的結(jié)果類型為: //IEnumerable<IGroup<string,car>>; //其中string等于car.type,也就是分組的鍵
第二步將IEnumerable類型轉(zhuǎn)化為字典,選取合適的鍵,
ToDictionary(r=>r.Key,r=>r.ToList());//r參數(shù)代表分組對象,r.Key便是car.type;//r.ToList()操作后將分組對象轉(zhuǎn)化為List對象
這種轉(zhuǎn)化代碼簡介,比以下foreach遍歷得到以car.type的字典簡潔許多:
var dict = new Dictionary<string,List<Car>>(); foreach(var car in cars) { if(dict.Contains(car.type)) dict[car.type].Add(car); else dict.Add(car.type,new List<Car>(){car})); }

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TheyieldkeywordinC#simplifiesiteratorcreationbyautomaticallygeneratingastatemachinethatenableslazyevaluation.1.Itallowsreturningitemsoneatatimeusingyieldreturn,pausingexecutionbetweeneachitem,whichisidealforlargeordynamicsequences.2.yieldbreakcanbeus

DependencyInjection(DI)inC#isadesignpatternthatenhancesmodularity,testability,andmaintainabilitybyallowingclassestoreceivedependenciesexternally.1.DIpromotesloosecouplingbydecouplingobjectcreationfromusage.2.Itsimplifiestestingthroughmockobjectinject

The role of IDisposable and using in C# is to efficiently and deterministically manage unmanaged resources. 1. IDisposable provides Dispose() method, so that the class can clearly define how to release unmanaged resources; 2. The using statement ensures that Dispose() is automatically called when the object is out of scope, simplifying resource management and avoiding leakage; 3. When using it, please note that the object must implement IDisposable, can declare multiple objects, and should always use using for types such as StreamReader; 4. Common best practices include not relying on destructors to clean up, correctly handling nested objects, and implementing the Dispose(bool) pattern.

LambdaexpressionsandLINQsimplifydatamanipulationinC#byenablingconcise,readable,andefficientcode.1.Lambdaexpressionsallowinlinefunctiondefinitions,makingiteasiertopasslogicasargumentsforfiltering,transforming,sorting,andaggregatingdatadirectlywithinme

Nullablereferencetypes(NRTs)inC#8 helpcatchNullReferenceExceptionerrorsatcompiletimebymakingreferencetypesnon-nullablebydefault,requiringexplicitdeclarationfornullability.NRTsmustbeenabledeitherinthe.csprojfilewithenableoratthetopofa.csfileusing#null

Span and Memory improve C# performance by reducing memory allocation. 1. Span avoids array copying and provides light references to existing memory, which is suitable for parsing binary protocols, string operations and high-performance buffer management; 2. Memory supports passing memory slices across asynchronous methods, which is suitable for scenarios where more flexible life cycles are required; 3. Both reduce GC pressure, optimize performance by reusing buffers and avoiding temporary copying; 4. Span is limited to use on the stack and cannot be stored in classes or used in asynchronous methods. Be careful to avoid reassignment operations such as calling.ToArray().

Four common "anti-pattern" problems in C# development need to be avoided. First, the unreasonable use of async/await leads to deadlocks or performance degradation. We should adhere to the principle of full asynchronousness, configure ConfigureAwait(false) and standardize naming; second, excessive dependence on var affects readability, and explicitly declare and unify team specifications when the type is unclear; third, the incorrect use of Dispose and resource management causes leakage, and the use statement should be used correctly and the IDisposable standard mode should be implemented; fourth, the abuse of static classes or singletons causes testing difficulties, and priority should be given to dependency injection, statelessness, or the life cycle managed by containers. Avoiding these misunderstandings can significantly improve code quality and maintenance.

SOLID principle is five design principles to improve code maintainability and scalability in object-oriented programming. They are: 1. The single responsibility principle (SRP) requires that the class only assumes one responsibility, such as separating report generation and email sending; 2. The opening and closing principle (OCP) emphasizes that the extension is supported through interfaces or abstract classes without modifying the original code, such as using the IShape interface to realize area calculation of different graphics; 3. The Richter replacement principle (LSP) requires that the subclass can replace the parent class without destroying logic, such as Square should not mistakenly inherit Rectangle, resulting in abnormal behavior; 4. The interface isolation principle (ISP) advocates the definition of fine-grained interfaces, such as split printing and scanning functions to avoid redundant dependencies; 5. The dependency inversion principle (DIP) advocates the
