Advertisement
j0k3r

martonx

Oct 31st, 2012
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace ConsoleApplication2
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             var list = new List<Test>
  12.             (
  13.                 new Test[]
  14.                 {
  15.                     new Test { Address = "Szeged", Email = "[email protected]", Name = "Szegedi Sandor"},
  16.                     new Test { Address = "Debrecen", Email = "[email protected]", Name = "Debreceni Jozsef"},
  17.                     new Test { Address = "Szeged", Email = "[email protected]", Name = "Szegedi Sandor"}
  18.                 }
  19.             );
  20.  
  21.             var szegediek = list.WhereContainsByField("Email", "szeg");
  22.  
  23.             foreach (var item in szegediek)
  24.             {
  25.                 Console.WriteLine(item.Email);
  26.             }
  27.  
  28.             Console.ReadLine();
  29.  
  30.         }
  31.     }
  32.  
  33.     public class Test
  34.     {
  35.         public string Name { get; set; }
  36.         public string Address { get; set; }
  37.         public string Email { get; set; }
  38.     }
  39.  
  40.     public static class ExtensionMethods
  41.     {
  42.         public static IEnumerable<T> WhereContainsByField<T>(this IEnumerable<T> collection, string propertyName, string textToFind)
  43.         {
  44.             Type type = typeof(T);
  45.             try
  46.             {
  47.                 if (type.GetProperty(propertyName) != null)
  48.                 {
  49.                     var collectionToReturn = new List<T>();
  50.  
  51.                     foreach (var item in collection)
  52.                     {
  53.                         var currentValue = type.GetProperty(propertyName).GetValue(item, null);
  54.                         if (currentValue.ToString().Contains(textToFind))
  55.                         {
  56.                             collectionToReturn.Add(item);
  57.                         }
  58.                     }
  59.  
  60.                     return collectionToReturn;
  61.                 }
  62.                 else
  63.                 {
  64.                     return Enumerable.Empty<T>();
  65.                 }
  66.             }
  67.             catch (Exception e)
  68.             {
  69.                 // todo
  70.                 Console.WriteLine(e.Message);
  71.                 return null;
  72.             }
  73.         }
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement