Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace ConsoleApplication2
- {
- class Program
- {
- static void Main(string[] args)
- {
- var list = new List<Test>
- (
- new Test[]
- {
- }
- );
- var szegediek = list.WhereContainsByField("Email", "szeg");
- foreach (var item in szegediek)
- {
- Console.WriteLine(item.Email);
- }
- Console.ReadLine();
- }
- }
- public class Test
- {
- public string Name { get; set; }
- public string Address { get; set; }
- public string Email { get; set; }
- }
- public static class ExtensionMethods
- {
- public static IEnumerable<T> WhereContainsByField<T>(this IEnumerable<T> collection, string propertyName, string textToFind)
- {
- Type type = typeof(T);
- try
- {
- if (type.GetProperty(propertyName) != null)
- {
- var collectionToReturn = new List<T>();
- foreach (var item in collection)
- {
- var currentValue = type.GetProperty(propertyName).GetValue(item, null);
- if (currentValue.ToString().Contains(textToFind))
- {
- collectionToReturn.Add(item);
- }
- }
- return collectionToReturn;
- }
- else
- {
- return Enumerable.Empty<T>();
- }
- }
- catch (Exception e)
- {
- // todo
- Console.WriteLine(e.Message);
- return null;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement