Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Fórum ➡ Filling in a DataTable from a list of KVP's ♦
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 #define DISPLAY_THE_TABLE_ROWS using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Data; // aljodav // http://rextester.com/users/376 // in reply to the MSDN thread // http://bit.ly/2eZsGWN namespace Rextester { using Data=KeyValuePair<int,string>; class Program { static DataTable GetTable(out string col0,out string col1,out string col2){ /*▶out◀*/col0="Id";col1="Value1";col2="Value2"; string[] titles={col0,col1,col2}; Type[] types={typeof(int),typeof(string),typeof(string)}; DataTable d=new DataTable(); d.Columns.AddRange(titles.Zip(types,(title,type)=>new DataColumn(title,type)).ToArray()); return d; } static List<Data> GetList(){ return new List<Data>{ new Data(1,"100"), new Data(1,"200"), new Data(2,"56789"), new Data(3,"30"), new Data(3,"10"), new Data(4,"210"), //new Data(1,"300"), // raises exception due to excessive # of fields with same Id. }; } public static void Main(string[] args) { string col0,col1,col2; DataTable table=GetTable(out col0,out col1,out col2); GetList() .GroupBy(kvp=>kvp.Key,kvp=>kvp.Value,(key,values)=>{ if(values.Count()>2)throw new Exception("‼✖ Excessive # of fields with same Id. ✖‼"); var array=values.ToArray(); DataRow row=table.NewRow(); row[col0]=key; row[col1]=array[0]; row[col2]=array.Length==2?array[1]:null as string; return row; }) .ToList() .ForEach(table.Rows.Add) ; #if DISPLAY_THE_TABLE_ROWS string fmt; Console.WriteLine((fmt="\t{0,3} {1,10} {2,10}"),col0,col1,col2); foreach(DataRow row in table.Rows)Console.WriteLine(fmt,row[col0],row[col1],row[col2]); #endif Console.WriteLine("\n\nHello, world!"); } } }
run
|
edit
|
history
|
help
0
math 10.97
"Live cooperation" problem fixed
t
Terminus Code Example 1
decimal to multiple binary
bc160401882
Bubble sort
Array 10th grade
xx
to find the first index of a substring in a given string