Previously, VAR query = xxx was used. select (C => New {C. x, C. y}); to get a two-column field in the Table. Today, an application needs to be converted to a dictionary <t, u>. It is rarely used in this way, and I forgot to write it!
I finally wrote it right after remembering it for a long time. I will paste it here to prepare a copy for Future Search:
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Namespace Dictest
{
Class Program
{
Static Void Main ( String [] ARGs)
{
List < Test > LST = New List < Test > ();
For ( Int I = 0 ; I < 10 ; I ++ )
{
Lst. Add ( New Test () {ID = Guid. newguid (), num = I, name = I. tostring ()});
}
Dictionary < Guid, Int > Dic = Lst. todictionary ( New Func < Test, guid > (C => C. ID ), New Func < Test, Int > (C => C. Num )); // If you think the writing method above is too complicated, it can be simplified // Dictionary <guid, int> DIC = lst. todictionary (C => C. ID, c => C. Num );
Foreach(Guid IDInDic. Keys)
{
Console. writeline ("Key: {0} \ tvalue: {1}", ID, DIC [ID]);
}
Console. Read ();
}
}
Public Class Test
{
Public Guid ID { Set ; Get ;}
Public Int Num { Set ; Get ;}
Public String Name { Set ; Get ;}
}
}
If you use reflector for reflection, you will find that the compiler automatically generatesCode(Some names are processed in a friendly way)
Code
[Compilergenerated]
Private Static Func < Test, guid > Funcguid;
[Compilergenerated]
Private Static Func < Test, Int > Funcint;
[Compilergenerated]
Private Static Int Mnum (test C)
{
Return C. Num;
}
[Compilergenerated]
Private Static Guid mid (test C)
{
Return C. ID;
}
Private Static Void Main ( String [] ARGs)
{
List < Test > LST = New List < Test > ();
For ( Int I = 0 ; I < 10 ; I ++ )
{
Test _ t = New Test ();
_ T. ID = Guid. newguid ();
_ T. Num = I;
_ T. Name = I. tostring ();
Lst. Add (_ t );
}
Dictionary < Guid, Int > Dic = Lst. todictionary < Test, guid, Int > (Funcguid ! = Null ) ? Funcguid: (funcguid = New Func < Test, guid > (Program. Mid), (funcint ! = Null ) ? Funcint: (funcint = New Func < Test, Int > (Program. mnum )));
Foreach (Guid ID In Dic. Keys)
{
Console. writeline ( " Key: {0} \ tvalue: {1} " , ID, DIC [ID]);
}
Console. Read ();
}
SELF: http://www.cnblogs.com/yjmyzz/archive/2009/12/04/1617240.html