English 中文(简体)
C# 核对阿雷拉小组的任何内容在比较长度之前是否为Null
原标题:C# Check if any element in an Array Group is Null before comparing length

我的发言比较了所有阵列中要素的长度。

string[][] allMyArrays= new string[][] { myArray1, myArray2, myArray3 };

lengthMismatch = allMyArrays.GroupBy(x => x.Length).Count() > 1;

但是,<代码>null exception,凡其中任何一项为null

我如何能够得出以下结果:<代码>lengthMismatch=false。 如果有

  1. Any, but not all arrays are null
  2. One or more array(s) length are not equal
最佳回答

您可以使用:

bool lengthMismatch = allMyArrays.GroupBy(x => x?.Length ?? int.MinValue).Count() > 1;

就此而言,你在空阵和空阵之间仍然有分歧。 如果全部无效,则按要求为<代码>false。

您还可以使用最佳方法,避免整个阵列的<条码>。

int firstLength = allMyArrays.FirstOrDefault()?.Length ?? int.MinValue;
bool anyDifferentLength = allMyArrays.Skip(1)
    .Any(arr => firstLength != (arr?.Length ?? int.MinValue));
问题回答

类似的情况是,LINQ认为冷却,但并不真正需要。

从业绩和可读性角度看,优良的<条码>(foreach)可能更好:

public static bool IsLengthMismatch(this string[][] arrays)
{
    int? lastLength = -1;

    foreach (var array in arrays)
    {
        if (lastLength != -1 && lastLength != array?.Length)
        {
            return true;
        }

        lastLength = array?.Length;
    }

    return false;
}

如果至少一个阵列不使用任何准则,则检查就无效。

string[][] allMyArrays = new string[][] { myArray1, myArray2, myArray3 };

bool atLeastOneNotNull = allMyArrays.Any(arr => arr != null);
bool allHaveEqualLength = allMyArrays.All(arr => arr?.Length == allMyArrays[0]?.Length);

bool lengthMismatch = atLeastOneNotNull && !allHaveEqualLength;

// lengthMismatch will be false if any, but not all arrays are null, and one or more array(s) have unequal lengths.




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签