// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Data; namespace E { public class Program { public static DataTable Create() { DataTable dt = new DataTable(); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Value", typeof(int)); dt.Rows.Add("John", 123); dt.Rows.Add("Alexander", 456); dt.Rows.Add("Bill", 789); return dt; } public static void Print(DataTable dt) { foreach(DataRow dr in dt.Rows) { foreach(object o in dr.ItemArray) { Console.Write(" " + o); } Console.WriteLine(); } } public static void Original(DataTable dt) { string expression = "Name = 'John'"; DataRow[] foundRows = dt.Select(expression); if (foundRows.Length == 0) { dt.Rows.Add("John", 0); } string expressionq = "Name = 'Jack'"; DataRow[] foundRowsq = dt.Select(expressionq); if (foundRowsq.Length == 0) { dt.Rows.Add("Jack", 0); } string expressionr = "Name = 'Mary'"; DataRow[] foundRowsr = dt.Select(expressionr); if (foundRowsr.Length == 0) { dt.Rows.Add("Mary", 0); } } private static void AddIfNotExists(DataTable dt, string name) { if(dt.Select("Name='" + name + "'").Length == 0) { dt.Rows.Add(name, 0); } } public static void Suggest(DataTable dt) { AddIfNotExists(dt, "John"); AddIfNotExists(dt, "Jack"); AddIfNotExists(dt, "Mary"); } public static void Main(string[] args) { DataTable dt1 = Create(); Original(dt1); Print(dt1); DataTable dt2 = Create(); Suggest(dt2); Print(dt2); } } }