垫LINQ的左侧或右侧连接是相同的行数 [英] Pad the left or right sides of a linq join to be the same number of rows

查看:99
本文介绍了垫LINQ的左侧或右侧连接是相同的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是建立一个列表是相同数量的右边行或向左,而不论是否在左列或右列比其它短

My goal is to create a list that is the same number of rows on the right or left, irrespective of if the left column or right column is shorter than the other.

考虑这两个查询:

var result1 = (from f in list2
               join b in list1 on f.index equals b.index into bf
               from x in bf.DefaultIfEmpty()
               select new { box = (x == null ? String.Empty : x.b), file = f.f });

var result2 = (from b in list1
              join f in list2 on b.index equals f.index into bf
              from x in bf.DefaultIfEmpty()
              select new { l1 = x.f, l2 = (x == null ? String.Empty : b.b) });

有关的list1的空单测试,并在一个空字符串罢了,其他的测试上列表2空并填补了一个空字符串。

One tests for null on the list1 and fills in an empty string, the other tests for null on list2 and fills in an empty string.

我想找到一个例子,两者都可以发生。顺序并不重要,只是在左侧的每个值或空字符串,对右边的值或空字符串。

I'd like to find an example where both can happen. The order is not important, just that every value or empty string on the left, has a value or empty string on the right.

推荐答案

它看起来像你需要一个版本的 IEnumerable.Zip 扩展方法的不停车时更短名单已经走到了尽头:

It looks like you need a version of the IEnumerable.Zip extension method that doesn't stop when the shorter list has reached its end:

public static IEnumerable<TResult> ZipAll<T, TResult>(this IEnumerable<T> list1,
                                                           IEnumerable<T> list2,
                                                           Func<T, T, TResult> zipper,
                                                           T defaultValue = default(T))
{
    using (var enum1 = list1.GetEnumerator())
    {
        using (var enum2 = list2.GetEnumerator())
        {

            bool valid1, valid2;
            do
            {
                valid1 = enum1.MoveNext();
                valid2 = enum2.MoveNext();
                if (valid1 || valid2)
                {
                    var item1 = valid1 ? enum1.Current : defaultValue;
                    var item2 = valid2 ? enum2.Current : defaultValue;

                    yield return zipper(item1, item2);
                }
            }
            while (valid1 || valid2);

        }
    }
}

..然后:

var result = list1.ZipAll(list2, (l1, l2) => new { l1, l2 }, string.Empty);

这篇关于垫LINQ的左侧或右侧连接是相同的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆