재우니의 블로그



List 제네릭을 LINQ 를 통해 WHERE 하기


var mFriends = new List<Friend>();
mFriends.Add(new Friend { FirstName = "Bob", LastName = "Smith", Age = "33", Gender = "Male" });
mFriends.Add(new Friend { FirstName = "Tom", LastName = "Smith", Age = "45", Gender = "Male" });
mFriends.Add(new Friend { FirstName = "Julie", LastName = "Smith", Age = "2020", Gender = "Unknown" });
mFriends.Add(new Friend { FirstName = "Molly", LastName = "Smith", Age = "21", Gender = "Female" });
mFriends.Add(new Friend { FirstName = "Joe", LastName = "Lopez", Age = "22", Gender = "Male" });
mFriends.Add(new Friend { FirstName = "Ruth", LastName = "White", Age = "81", Gender = "Female" });
mFriends.Add(new Friend { FirstName = "Sally", LastName = "Johnson", Age = "54", Gender = "Female" });


List<Friend> searchedFriends = (from friend in mFriends
    where friend.FirstName.Contains(mSearch.Text, StringComparison.OrdinalIgnoreCase) || friend.LastName.Contains(mSearch.Text, StringComparison.OrdinalIgnoreCase)
    || friend.Age.Contains(mSearch.Text, StringComparison.OrdinalIgnoreCase) || friend.Gender.Contains(mSearch.Text, StringComparison.OrdinalIgnoreCase)
    select friend).ToList<Friend>();

    


Contains 에 대한 확장메소드는 아래와 같습니다.


using System;
using System.Collections.Generic;
using System.Text;

namespace AnimationTutorial
{
    public static class ExtMethods
    {
        public static bool Contains (this string source, string toCheck, StringComparison comparisonType)
        {
            return (source.IndexOf(toCheck, comparisonType) >= 0);
        }
    }
}