LEFT OUTER JOIN in LINQ

后端 未结 22 2443
臣服心动
臣服心动 2020-11-21 04:49

How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause? Corr

22条回答
  •  清酒与你
    2020-11-21 05:37

    Extension method that works like left join with Join syntax

    public static class LinQExtensions
    {
        public static IEnumerable LeftJoin(
            this IEnumerable outer, IEnumerable inner, 
            Func outerKeySelector, 
            Func innerKeySelector, 
            Func resultSelector)
        {
            return outer.GroupJoin(
                inner, 
                outerKeySelector, 
                innerKeySelector,
                (outerElement, innerElements) => resultSelector(outerElement, innerElements.FirstOrDefault()));
        }
    }
    

    just wrote it in .NET core and it seems to be working as expected.

    Small test:

            var Ids = new List { 1, 2, 3, 4};
            var items = new List>
            {
                new Tuple(1,"a"),
                new Tuple(2,"b"),
                new Tuple(4,"d"),
                new Tuple(5,"e"),
            };
    
            var result = Ids.LeftJoin(
                items,
                id => id,
                item => item.Item1,
                (id, item) => item ?? new Tuple(id, "not found"));
    
            result.ToList()
            Count = 4
            [0]: {(1, a)}
            [1]: {(2, b)}
            [2]: {(3, not found)}
            [3]: {(4, d)}
    

提交回复
热议问题