// 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 { 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 class Data2 { public Data D { get; set; } public string E { get; set; } public override string ToString() { return string.Format("{{D={0},E={1}}}", D, E); } } public interface IFilter { bool Accept(Dictionary filter, T o); } public class Data1Filter : IFilter { public bool Accept(Dictionary filter, Data1 o) { return (o.A.V1 == (filter.Get("A.V1") ?? o.A.V1)) && (o.A.V2 == (filter.Get("A.V2") ?? o.A.V2)) && (o.B == (filter.Get("B") ?? o.B)) && (o.C == (filter.Get("C") ?? o.C)); } } public class Data2Filter : IFilter { public bool Accept(Dictionary filter, Data2 o) { return (o.D.V1 == (filter.Get("D.V1") ?? o.D.V1)) && (o.D.V2 == (filter.Get("D.V2") ?? o.D.V2)) && (o.E == (filter.Get("E") ?? o.E)); } } 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, IFilter filter, Dictionary filtervals) { return lst.Where(o => filter.Accept(filtervals, o)).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(new Data1Filter(), flt1)) { Console.WriteLine(o); } Dictionary flt2 = new Dictionary(); flt2.Add("A.V1", "6DV1"); flt2.Add("E", "6E"); foreach(Data2 o in lst2.Filter(new Data2Filter(), flt2)) { Console.WriteLine(o); } } } }