Advertisement
Guest User

chakrit

a guest
Feb 28th, 2009
646
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Windows.Forms;
  7.  
  8. static class Program
  9. {
  10.  
  11.     static void Main()
  12.     {
  13.         var data = new[] {
  14.                 new DataItem { Title = "Hello", Contents = "World" },
  15.                 new DataItem { Title = "Stack", Contents = "Overflow" },
  16.                 new DataItem { Title = "SO", Contents = "SO" },
  17.                 new DataItem { Title = "Non", Contents = "Hello" },
  18.                 new DataItem { Title = "Non", Contents = "Stack" },
  19.                 new DataItem { Title = "Non", Contents = "Non" }
  20.             }.AsEnumerable();
  21.  
  22.         // our custom predicate builders
  23.         Func<string, Func<DataItem, bool>> buildKeywordPredicate =
  24.             keyword =>
  25.                 x => x.Title.Contains(keyword)
  26.                     || x.Contents.Contains(keyword);
  27.  
  28.         Func<Func<DataItem,bool>, Func<DataItem, bool>, Func<DataItem, bool>> buildOrPredicate =
  29.             (pred1, pred2) =>
  30.                 x => pred1(x) || pred2(x);
  31.  
  32.         var keywords = new[] { "Hello", "Stack" };
  33.  
  34.         // build the WHERE filter
  35.         Func<DataItem, bool> filter = null;
  36.  
  37.         foreach (var word in keywords) {            
  38.             filter = filter == null
  39.                 ? buildKeywordPredicate(word)
  40.                 : buildOrPredicate(filter, buildKeywordPredicate(word));
  41.         }
  42.  
  43.         // and apply it
  44.         var result = data.Where(filter);
  45.  
  46.         // verify results
  47.         foreach (var item in result) {
  48.             Console.WriteLine(item.ToString());
  49.         }
  50.  
  51.         Console.ReadKey();
  52.     }
  53.  
  54.     public class DataItem
  55.     {
  56.         public string Title { get; set; }
  57.         public string Contents { get; set; }
  58.  
  59.         public override string ToString()
  60.         {
  61.             return string.Format("Title = {0}, Contents = {1}", Title, Contents);
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement