linq中join的用法

join方法

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
	this IEnumerable<TOuter> outer,
	IEnumerable<TInner> inner,
	Func<TOuter, TKey> outerKeySelector,
	Func<TInner, TKey> innerKeySelector,
	Func<TOuter, TInner, TResult> resultSelector
)
outerKeySelector是指要参与比较的第一个序列的元素,
innerKeySelector是指要参与比较的第二个序列的元素,
Func<TOuter, TInner, TResult> resultSelector常用一个匿名函数作为透射出来的结果集,
重载方法的最后一个参数IEqualityComparer<TKey>则是这两个元素的默认比较器。

示例代码:
class Program
    {
        static void Main(string[] args)
        {
            List<Person> persons = new List<Person> { new Person { Id = 1, Name = "John" }, new Person { Id = 2, Name = "Mark" }, new Person { Id = 3, Name = "Luke" } };
            List<PersonInfo> personInfos = new List<PersonInfo> { new PersonInfo() { Id = "0", PersonId = 1, Gender = "Male" }, new PersonInfo() { Id = "1", PersonId = 2, Gender = "Female" } };
            var query = persons.Join(personInfos, a => a.Id, b => b.
                PersonId,
                         (a, b) => new { PersonName = a.Name, PersonGender = b.Gender });
            foreach (var s in query)
            {
                Console.WriteLine(s.PersonGender + " " + s.PersonName);
            }
            Console.ReadKey();
        }


    }
    class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class PersonInfo
    {
        public string Id { get; set; }
        public int PersonId { get; set; }
        public string Gender { get; set; }
    }

 

posted @ 2013-07-30 10:06  瓜王  阅读(2907)  评论(0编辑  收藏  举报