// 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.Collections.Generic; using System.Linq; namespace E { public class Data { public string V1 { get; set; } public string V2 { get; set; } public override string ToString() { return string.Format("{{V1={0},V2={1}}}", V1, V2); } } public class Data1 : IFiltrable { public Data A { get; set; } public string B { get; set; } public string C { get; set; } public override string ToString() { return string.Format("{{A={0},B={1},C={2}}}", A, B, C); } public bool Accept(Dictionary filter) { return (A.V1 == (filter.Get("A.V1") ?? A.V1)) && (A.V2 == (filter.Get("A.V2") ?? A.V2)) && (B == (filter.Get("B") ?? B)) && (C == (filter.Get("C") ?? C)); } } public class Data2 : IFiltrable { public Data D { get; set; } public string E { get; set; } public override string ToString() { return string.Format("{{D={0},E={1}}}", D, E); } public bool Accept(Dictionary filter) { return (D.V1 == (filter.Get("D.V1") ?? D.V1)) && (D.V2 == (filter.Get("D.V2") ?? D.V2)) && (E == (filter.Get("E") ?? E)); } } public interface IFiltrable { bool Accept(Dictionary filter); } public static class Util { public static TV Get(this Dictionary d, TK key) where TV : class { if(d.ContainsKey(key)) { return d[key]; } else { return null; } } public static List Filter(this List lst, Dictionary filtervals) where T : IFiltrable { return lst.Where(o => o.Accept(filtervals)).ToList(); } } public class Program { public static void Main(string[] args) { List lst1 = new List { new Data1 { A = new Data { V1 = "1AV1", V2 = "1AV2" }, B = "1B", C = "1C" }, new Data1 { A = new Data { V1 = "2AV1", V2 = "2AV2" }, B = "2B", C = "2C" }, new Data1 { A = new Data { V1 = "3AV1", V2 = "3AV2" }, B = "3B", C = "3C" } }; List lst2 = new List { new Data2 { D = new Data { V1 = "4DV1", V2 = "4DV2" }, E = "4E" }, new Data2 { D = new Data { V1 = "5DV1", V2 = "5DV2" }, E = "5E" }, new Data2 { D = new Data { V1 = "6DV1", V2 = "6DV2" }, E = "6E" } }; foreach(Data1 o in lst1) { Console.WriteLine(o); } foreach(Data2 o in lst2) { Console.WriteLine(o); } Dictionary flt1 = new Dictionary(); flt1.Add("A.V2", "2AV2"); foreach(Data1 o in lst1.Filter(flt1)) { Console.WriteLine(o); } Dictionary flt2 = new Dictionary(); flt2.Add("A.V1", "6DV1"); flt2.Add("E", "6E"); foreach(Data2 o in lst2.Filter(flt2)) { Console.WriteLine(o); } } } }