C# Linq实现内连接、左连接

C#中用EF框架做数据查询时,目前只有内连接的相关方法,可以扩展Linq的方法实现相关的左连接(右连接只是参数位置不同即可实现),以下是相关扩展IEnumerable实现Linq的内连接和左连接的方法:

    public static class IEnumerableEntends
    {

        public static IEnumerable Joins(this IEnumerable outer, IEnumerable inner, Func MatchDelegate, Func resultSelector)
        {

            foreach (TOuter to in outer)
            {
                foreach (TInner ti in inner)
                {

                    if (MatchDelegate(to, ti))
                    {
                        yield return resultSelector(to, ti);
                    }

                }
            }

        }

        public static IEnumerable LeftJoins(this IEnumerable outer, IEnumerable inner, Func MatchDelegate, Func resultSelector)
        {

            foreach (TOuter to in outer)
            {
                bool matched = false;
                foreach (TInner ti in inner)
                {

                    if (MatchDelegate(to, ti))
                    {
                        matched = true;
                        yield return resultSelector(to, ti);
                    }

                }

                if (!matched)
                {
                    yield return resultSelector(to, default(TInner));
                }
            }

        }

        public static IEnumerable LeftJoin(this IEnumerable outer, IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector)
        {
            foreach (TOuter to in outer)
            {
                TKey outkey = outerKeySelector(to);
                bool matched = false;

                foreach (TInner ti in inner)
                {

                    //fix bug: TKey inkey = outerKeySelector(to);
                    TKey inkey = innerKeySelector(ti);

                    if (outkey.Equals(inkey))
                    {
                        matched = true;
                        yield return resultSelector(to, ti);
                    }
                }

                if (!matched)
                {
                    yield return resultSelector(to, default(TInner));
                }
            }
        }

    }

你可能感兴趣的:(.Net)