Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Windows.Forms;
- static class Program
- {
- static void Main()
- {
- var data = new[] {
- new DataItem { Title = "Hello", Contents = "World" },
- new DataItem { Title = "Stack", Contents = "Overflow" },
- new DataItem { Title = "SO", Contents = "SO" },
- new DataItem { Title = "Non", Contents = "Hello" },
- new DataItem { Title = "Non", Contents = "Stack" },
- new DataItem { Title = "Non", Contents = "Non" }
- }.AsEnumerable();
- // our custom predicate builders
- Func<string, Func<DataItem, bool>> buildKeywordPredicate =
- keyword =>
- x => x.Title.Contains(keyword)
- || x.Contents.Contains(keyword);
- Func<Func<DataItem,bool>, Func<DataItem, bool>, Func<DataItem, bool>> buildOrPredicate =
- (pred1, pred2) =>
- x => pred1(x) || pred2(x);
- var keywords = new[] { "Hello", "Stack" };
- // build the WHERE filter
- Func<DataItem, bool> filter = null;
- foreach (var word in keywords) {
- filter = filter == null
- ? buildKeywordPredicate(word)
- : buildOrPredicate(filter, buildKeywordPredicate(word));
- }
- // and apply it
- var result = data.Where(filter);
- // verify results
- foreach (var item in result) {
- Console.WriteLine(item.ToString());
- }
- Console.ReadKey();
- }
- public class DataItem
- {
- public string Title { get; set; }
- public string Contents { get; set; }
- public override string ToString()
- {
- return string.Format("Title = {0}, Contents = {1}", Title, Contents);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement