Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Fórum ➡ Filling in a DataTable from a list of KVP's ♦
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//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!"); } } }
Show compiler warnings
[
+
]
Show input
Compilation time: 0,17 sec, absolute running time: 0,2 sec, cpu time: 0,2 sec, average memory usage: 19 Mb, average nr of threads: 4
edit mode
|
history
|
discussion
Id Value1 Value2 1 100 200 2 56789 3 30 10 4 210 Hello, world!