如何检查 IEnumerable 是否为 null 或为空?

发布于 2024-10-18 06:32:37 字数 340 浏览 2 评论 0原文

我喜欢 string.IsNullOrEmpty 方法。我希望有一些东西可以为 IEnumerable 提供相同的功能。有这样的吗?也许是一些集合助手类?我问的原因是,在 if 语句中,如果模式是 (mylist != null && mylist.Any()),代码看起来会很混乱。使用 Foo.IsAny(myList) 会更干净。

这篇文章没有给出这个答案:IEnumerable 是空的?

I love string.IsNullOrEmpty method. I'd love to have something that would allow the same functionality for IEnumerable. Is there such? Maybe some collection helper class? The reason I am asking is that in if statements the code looks cluttered if the patter is (mylist != null && mylist.Any()). It would be much cleaner to have Foo.IsAny(myList).

This post doesn't give that answer: IEnumerable is empty?.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

我是有多爱你 2024-10-25 06:32:37

当然,您可以这样写:

public static class Utils {
    public static bool IsAny<T>(this IEnumerable<T> data) {
        return data != null && data.Any();
    }
}

但是,请注意并非所有序列都是可重复的; 通常我宁愿只走一次,以防万一。

Sure you could write that:

public static class Utils {
    public static bool IsAny<T>(this IEnumerable<T> data) {
        return data != null && data.Any();
    }
}

however, be cautious that not all sequences are repeatable; generally I prefer to only walk them once, just in case.

旧人哭 2024-10-25 06:32:37
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) {
    return enumerable == null || !enumerable.Any();
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) {
    return enumerable == null || !enumerable.Any();
}
-黛色若梦 2024-10-25 06:32:37

这是 @Matt Greer 的有用答案的修改版本,其中包含一个静态包装类,因此您只需将其复制粘贴到新的源文件中,不依赖于 Linq,并添加一个通用的 IEnumerable重载,以避免非泛型版本中发生的值类型装箱。 [编辑:请注意,使用 IEnumerable 不会阻止枚举器装箱,鸭子类型 无法阻止这种情况,但至少值类型集合中的元素不会被装箱。]

using System.Collections;
using System.Collections.Generic;

public static class IsNullOrEmptyExtension
{
    public static bool IsNullOrEmpty(this IEnumerable source)
    {
        if (source != null)
        {
            foreach (object obj in source)
            {
                return false;
            }
        }
        return true;
    }

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
    {
        if (source != null)
        {
            foreach (T obj in source)
            {
                return false;
            }
        }
        return true;
    }
}

Here's a modified version of @Matt Greer's useful answer that includes a static wrapper class so you can just copy-paste this into a new source file, doesn't depend on Linq, and adds a generic IEnumerable<T> overload, to avoid the boxing of value types that would occur with the non-generic version. [EDIT: Note that use of IEnumerable<T> does not prevent boxing of the enumerator, duck-typing can't prevent that, but at least the elements in a value-typed collection will not each be boxed.]

using System.Collections;
using System.Collections.Generic;

public static class IsNullOrEmptyExtension
{
    public static bool IsNullOrEmpty(this IEnumerable source)
    {
        if (source != null)
        {
            foreach (object obj in source)
            {
                return false;
            }
        }
        return true;
    }

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
    {
        if (source != null)
        {
            foreach (T obj in source)
            {
                return false;
            }
        }
        return true;
    }
}
没有心的人 2024-10-25 06:32:37
if (collection?.Any() == true)
{
    // if collection contains one or more items
}
if (collection?.Any() != true) // note == false won't work
{
    // if collection is null
    // if collection does not contain any item
}
if (collection?.Any() == true)
{
    // if collection contains one or more items
}
if (collection?.Any() != true) // note == false won't work
{
    // if collection is null
    // if collection does not contain any item
}
最终幸福 2024-10-25 06:32:37

另一种方法是获取 Enumerator 并调用 MoveNext() 方法来查看是否有任何项目:

if (mylist != null && mylist.GetEnumerator().MoveNext())
{
    // The list is not null or empty
}

这适用于 IEnumerable 以及 IEnumerable

Another way would be to get the Enumerator and call the MoveNext() method to see if there are any items:

if (mylist != null && mylist.GetEnumerator().MoveNext())
{
    // The list is not null or empty
}

This works for IEnumerable as well as IEnumerable<T>.

扛刀软妹 2024-10-25 06:32:37

我这样做的方式是利用一些现代 C# 功能:

选项 1)

public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any() ?? false);
    }
}

选项 2)

public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any()).GetValueOrDefault();
    }
}

顺便说一下,永远不要使用 Count == 0Count() == 0 code> 只是检查集合是否为空。始终使用 Linq 的 .Any()

The way I do it, taking advantage of some modern C# features:

Option 1)

public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any() ?? false);
    }
}

Option 2)

public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any()).GetValueOrDefault();
    }
}

And by the way, never use Count == 0 or Count() == 0 just to check if a collection is empty. Always use Linq's .Any()

心房的律动 2024-10-25 06:32:37

从 C#6 开始,您可以使用 空传播< /a>: myList?.Any() == true

如果您仍然觉得这太堵塞或者更喜欢好的 ol' 扩展方法,我会推荐 Matt Greer 和 Marc Gravell 的答案,但有一点扩展功能的完整性。

他们的答案提供了相同的基本功能,但各自从不同的角度来看。马特的答案使用 string.IsNullOrEmpty-心态,而 Marc 的答案则采用 Linq 的 .Any() 方式来完成工作。

我个人倾向于使用 。 Any() 道路,但希望从该方法的 其他重载

    public static bool AnyNotNull<T>(this IEnumerable<T> source, Func<T, bool> predicate = null)
    {
        if (source == null) return false;
        return predicate == null
            ? source.Any()
            : source.Any(predicate);
    }

因此您仍然可以执行以下操作:
myList.AnyNotNull(item=>item.AnswerToLife == 42); 就像使用常规 .Any() 一样,但添加了 null 检查

请注意,使用C#6方式:myList?.Any()返回的是bool?而不是bool,这是的实际效果传播 null

Starting with C#6 you can use null propagation: myList?.Any() == true

If you still find this too cloggy or prefer a good ol' extension method, I would recommend Matt Greer and Marc Gravell's answers, yet with a bit of extended functionality for completeness.

Their answers provide the same basic functionality, but each from another perspective. Matt's answer uses the string.IsNullOrEmpty-mentality, whereas Marc's answer takes Linq's .Any() road to get the job done.

I am personally inclined to use the .Any() road, but would like to add the condition checking functionality from the method's other overload:

    public static bool AnyNotNull<T>(this IEnumerable<T> source, Func<T, bool> predicate = null)
    {
        if (source == null) return false;
        return predicate == null
            ? source.Any()
            : source.Any(predicate);
    }

So you can still do things like :
myList.AnyNotNull(item=>item.AnswerToLife == 42); as you could with the regular .Any() but with the added null check

Note that with the C#6 way: myList?.Any() returns a bool? rather than a bool, which is the actual effect of propagating null

心的位置 2024-10-25 06:32:37

这可能有帮助

public static bool IsAny<T>(this IEnumerable<T> enumerable)
{
    return enumerable?.Any() == true;
}

public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
    return enumerable?.Any() != true;
}

This may help

public static bool IsAny<T>(this IEnumerable<T> enumerable)
{
    return enumerable?.Any() == true;
}

public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
    return enumerable?.Any() != true;
}
蓝眼泪 2024-10-25 06:32:37

当涉及引用(可为空)类型并且项目中不存在空项目时,可以使用这一行进行验证

myCollection?.FirstOrDefault() == null

One can use this line for that verification when it's about reference (nullable) types and when no null item expected among the items

myCollection?.FirstOrDefault() == null
无敌元气妹 2024-10-25 06:32:37

Jon Skeet 的 anwser (https://stackoverflow.com/a/28904021/8207463) 有一个使用扩展方法的好方法 - Any() 表示 NULL 和 EMPTY。但他正在验证问题的所有者以防 NOT NULL。
因此,请小心地将 Jon 验证 AS NULL 的方法更改为:

If (yourList?.Any() != true) 
{
     ..your code...
}

请勿使用(不会验证 AS NULL):

If (yourList?.Any() == false) 
{
     ..your code...
}

您还可以在验证 AS NOT NULL 的情况下(未作为示例进行测试,但没有编译器错误)执行类似于使用谓词的操作:

If (yourList?.Any(p => p.anyItem == null) == true) 
{
     ..your code...
}

https://referencesource.microsoft.com/#System。 Core/System/Linq/Enumerable.cs,8788153112b7ffd0

对于您可以使用的 .NET 版本,请检查:

https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable .any?view=netframework-4.8#moniker-applies-to

Jon Skeet's anwser (https://stackoverflow.com/a/28904021/8207463) has a good approach using Extension Method - Any() for NULL and EMPTY. BUT he´s validating the questions´owner in case for NOT NULL.
So carefully change Jon´s approach to validate AS NULL to:

If (yourList?.Any() != true) 
{
     ..your code...
}

DO NOT use ( will not validate AS NULL):

If (yourList?.Any() == false) 
{
     ..your code...
}

You can also in case validating AS NOT NULL ( NOT tested just as example but without compiler error) do something like using predicate :

If (yourList?.Any(p => p.anyItem == null) == true) 
{
     ..your code...
}

https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8788153112b7ffd0

For which .NET version you can use it please check:

https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netframework-4.8#moniker-applies-to

枕头说它不想醒 2024-10-25 06:32:37

以下是 Marc Gravell 的回答中的代码,以及使用它的示例。

using System;
using System.Collections.Generic;
using System.Linq;

public static class Utils
{
    public static bool IsAny<T>(this IEnumerable<T> data)
    {
        return data != null && data.Any();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items;
        //items = null;
        //items = new String[0];
        items = new String[] { "foo", "bar", "baz" };

        /*** Example Starts Here ***/
        if (items.IsAny())
        {
            foreach (var item in items)
            {
                Console.WriteLine(item);
            }
        }
        else
        {
            Console.WriteLine("No items.");
        }
    }
}

正如他所说,并非所有序列都是可重复的,因此代码有时可能会导致问题,因为 IsAny() 开始逐步执​​行序列。我怀疑 Robert Harvey 的回答 的意思是您通常不需要检查 null 空。通常,您可以只检查 null,然后使用 foreach

为了避免启动序列两次并利用 foreach,我只编写了一些如下代码:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items;
        //items = null;
        //items = new String[0];
        items = new String[] { "foo", "bar", "baz" };

        /*** Example Starts Here ***/
        bool isEmpty = true;
        if (items != null)
        {
            foreach (var item in items)
            {
                isEmpty = false;
                Console.WriteLine(item);
            }
        }
        if (isEmpty)
        {
            Console.WriteLine("No items.");
        }
    }
}

我猜扩展方法可以为您节省几行输入,但这段代码对我来说似乎更清晰。我怀疑一些开发人员不会立即意识到 IsAny(items) 实际上会开始逐步执​​行该序列。 (当然,如果您使用大量序列,您很快就会学会思考其中的步骤。)

Here's the code from Marc Gravell's answer, along with an example of using it.

using System;
using System.Collections.Generic;
using System.Linq;

public static class Utils
{
    public static bool IsAny<T>(this IEnumerable<T> data)
    {
        return data != null && data.Any();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items;
        //items = null;
        //items = new String[0];
        items = new String[] { "foo", "bar", "baz" };

        /*** Example Starts Here ***/
        if (items.IsAny())
        {
            foreach (var item in items)
            {
                Console.WriteLine(item);
            }
        }
        else
        {
            Console.WriteLine("No items.");
        }
    }
}

As he says, not all sequences are repeatable, so that code may sometimes cause problems, because IsAny() starts stepping through the sequence. I suspect what Robert Harvey's answer meant was that you often don't need to check for null and empty. Often, you can just check for null and then use foreach.

To avoid starting the sequence twice and take advantage of foreach, I just wrote some code like this:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items;
        //items = null;
        //items = new String[0];
        items = new String[] { "foo", "bar", "baz" };

        /*** Example Starts Here ***/
        bool isEmpty = true;
        if (items != null)
        {
            foreach (var item in items)
            {
                isEmpty = false;
                Console.WriteLine(item);
            }
        }
        if (isEmpty)
        {
            Console.WriteLine("No items.");
        }
    }
}

I guess the extension method saves you a couple of lines of typing, but this code seems clearer to me. I suspect that some developers wouldn't immediately realize that IsAny(items) will actually start stepping through the sequence. (Of course if you're using a lot of sequences, you quickly learn to think about what steps through them.)

全部不再 2024-10-25 06:32:37

我使用 Bool IsCollectionNullOrEmpty = !(Collection?.Any()??false);。希望这有帮助。

细分:

如果 Collection 为 null,则 Collection?.Any() 将返回 null;如果 Collection 为空,则返回 false

如果 Collection 为空,Collection?.Any()??false 将为我们提供 false;如果 Collection 为 null,则为 false代码>.

对此的补充将为我们提供 IsEmptyOrNull

I use Bool IsCollectionNullOrEmpty = !(Collection?.Any()??false);. Hope this helps.

Breakdown:

Collection?.Any() will return null if Collection is null, and false if Collection is empty.

Collection?.Any()??false will give us false if Collection is empty, and false if Collection is null.

Complement of that will give us IsEmptyOrNull.

萌酱 2024-10-25 06:32:37

我遇到了同样的问题,我解决它的方式如下:

    public bool HasMember(IEnumerable<TEntity> Dataset)
    {
        return Dataset != null && Dataset.Any(c=>c!=null);
    }

“c=>c!=null”将忽略所有空实体。

I had the same problem and I solve it like :

    public bool HasMember(IEnumerable<TEntity> Dataset)
    {
        return Dataset != null && Dataset.Any(c=>c!=null);
    }

"c=>c!=null" will ignore all the null entities.

纸伞微斜 2024-10-25 06:32:37

我是根据@Matt Greer的回答构建的,

他完美地回答了OP的问题。

我想要这样的东西,同时保持 Any 的原始功能,同时检查 null 。我发布这个以防其他人需要类似的东西。

具体来说,我希望仍然能够传递谓词。

public static class Utilities
{
    /// <summary>
    /// Determines whether a sequence has a value and contains any elements.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">The <see cref="System.Collections.Generic.IEnumerable"/> to check for emptiness.</param>
    /// <returns>true if the source sequence is not null and contains any elements; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source?.Any() == true;
    }

    /// <summary>
    /// Determines whether a sequence has a value and any element of a sequence satisfies a condition.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">An <see cref="System.Collections.Generic.IEnumerable"/> whose elements to apply the predicate to.</param>
    /// <param name="predicate">A function to test each element for a condition.</param>
    /// <returns>true if the source sequence is not null and any elements in the source sequence pass the test in the specified predicate; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        return source?.Any(predicate) == true;
    }
}

扩展方法的命名可能会更好。

I built this off of the answer by @Matt Greer

He answered the OP's question perfectly.

I wanted something like this while maintaining the original capabilities of Any while also checking for null. I'm posting this in case anyone else needs something similar.

Specifically I wanted to still be able to pass in a predicate.

public static class Utilities
{
    /// <summary>
    /// Determines whether a sequence has a value and contains any elements.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">The <see cref="System.Collections.Generic.IEnumerable"/> to check for emptiness.</param>
    /// <returns>true if the source sequence is not null and contains any elements; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source?.Any() == true;
    }

    /// <summary>
    /// Determines whether a sequence has a value and any element of a sequence satisfies a condition.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">An <see cref="System.Collections.Generic.IEnumerable"/> whose elements to apply the predicate to.</param>
    /// <param name="predicate">A function to test each element for a condition.</param>
    /// <returns>true if the source sequence is not null and any elements in the source sequence pass the test in the specified predicate; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        return source?.Any(predicate) == true;
    }
}

The naming of the extension method could probably be better.

傲鸠 2024-10-25 06:32:37

只需添加 using System.Linq 并在您尝试访问 IEnumerable 中的可用方法时看到奇迹发生。添加它将使您能够访问名为 Count() 的方法,就这么简单。只需记住在调用 count() 之前检查 null 值 :)

just add using System.Linq and see the magic happening when you try to access the available methods in the IEnumerable. Adding this will give you access to method named Count() as simple as that. just remember to check for null value before calling count() :)

星光不落少年眉 2024-10-25 06:32:37

我使用简单的 if 来检查它,

看看我的解决方案

foreach (Pet pet in v.Pets)
{
    if (pet == null)
    {
        Console.WriteLine(" No pet");// enumerator is empty
        break;
    }
    Console.WriteLine("  {0}", pet.Name);
}

I used simple if to check for it

check out my solution

foreach (Pet pet in v.Pets)
{
    if (pet == null)
    {
        Console.WriteLine(" No pet");// enumerator is empty
        break;
    }
    Console.WriteLine("  {0}", pet.Name);
}
一紙繁鸢 2024-10-25 06:32:37

下面的另一个最佳解决方案来检查是否为空?

for(var item in listEnumerable)
{
 var count=item.Length;
  if(count>0)
  {
         // not empty or null
   }
  else
  {
       // empty
  }
}

The other best solution as below to check empty or not ?

for(var item in listEnumerable)
{
 var count=item.Length;
  if(count>0)
  {
         // not empty or null
   }
  else
  {
       // empty
  }
}
财迷小姐 2024-10-25 06:32:37

我用的是这个:

    public static bool IsNotEmpty(this ICollection elements)
    {
        return elements != null && elements.Count > 0;
    }

Ejem:

List<string> Things = null;
if (Things.IsNotEmpty())
{
    //replaces ->  if (Things != null && Things.Count > 0) 
}

I use this one:

    public static bool IsNotEmpty(this ICollection elements)
    {
        return elements != null && elements.Count > 0;
    }

Ejem:

List<string> Things = null;
if (Things.IsNotEmpty())
{
    //replaces ->  if (Things != null && Things.Count > 0) 
}
杀お生予夺 2024-10-25 06:32:37

由于有些资源读完就耗尽了,我想为什么不把检查和读结合起来,而不是传统的单独检查,然后读。

首先,我们有一个更简单的 check-for-null 内联扩展:

public static System.Collections.Generic.IEnumerable<T> ThrowOnNull<T>(this System.Collections.Generic.IEnumerable<T> source, string paramName = null) => source ?? throw new System.ArgumentNullException(paramName ?? nameof(source));

var first = source.ThrowOnNull().First();

然后我们有更多的参与(嗯,至少是我编写的方式) check-for-null-and-empty 内联扩展:

public static System.Collections.Generic.IEnumerable<T> ThrowOnNullOrEmpty<T>(this System.Collections.Generic.IEnumerable<T> source, string paramName = null)
{
  using (var e = source.ThrowOnNull(paramName).GetEnumerator())
  {
    if (!e.MoveNext())
    {
      throw new System.ArgumentException(@"The sequence is empty.", paramName ?? nameof(source));
    }

    do
    {
      yield return e.Current;
    }
    while (e.MoveNext());
  }
}

var first = source.ThrowOnNullOrEmpty().First();

你当然仍然可以调用两者而不继续调用链。另外,我还包含了 paramName,以便调用者可以在未检查“源”的情况下包含错误的备用名称,例如“nameof(target)”。

Since some resources are exhausted after one read, I thought why not combine the checks and the reads, instead of the traditional separate check, then read.

First we have one for the simpler check-for-null inline extension:

public static System.Collections.Generic.IEnumerable<T> ThrowOnNull<T>(this System.Collections.Generic.IEnumerable<T> source, string paramName = null) => source ?? throw new System.ArgumentNullException(paramName ?? nameof(source));

var first = source.ThrowOnNull().First();

Then we have the little more involved (well, at least the way I wrote it) check-for-null-and-empty inline extension:

public static System.Collections.Generic.IEnumerable<T> ThrowOnNullOrEmpty<T>(this System.Collections.Generic.IEnumerable<T> source, string paramName = null)
{
  using (var e = source.ThrowOnNull(paramName).GetEnumerator())
  {
    if (!e.MoveNext())
    {
      throw new System.ArgumentException(@"The sequence is empty.", paramName ?? nameof(source));
    }

    do
    {
      yield return e.Current;
    }
    while (e.MoveNext());
  }
}

var first = source.ThrowOnNullOrEmpty().First();

You can of course still call both without continuing the call chain. Also, I included the paramName, so that the caller may include an alternate name for the error if it's not "source" being checked, e.g. "nameof(target)".

天涯离梦残月幽梦 2024-10-25 06:32:37
 public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source != null && source.Any();
    }

我自己的扩展方法来检查 Not null 和 Any

 public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source != null && source.Any();
    }

my own extension method to check Not null and Any

卷耳 2024-10-25 06:32:37

如果没有自定义助手,我推荐 ?.Any() ?? false?.Any() == true 比较简洁,只需要指定一次序列。


当我想将丢失的集合视为空集合时,我使用以下扩展方法:

public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> sequence)
{
    return sequence ?? Enumerable.Empty<T>();
}

此函数可以与所有 LINQ 方法和 foreach 结合使用,而不仅仅是 .Any(),这就是为什么我更喜欢它而不是人们在这里提出的更专业的帮助函数。

Without custom helpers I recommend either ?.Any() ?? false or ?.Any() == true which are relatively concise and only need to specify the sequence once.


When I want to treat a missing collection like an empty one, I use the following extension method:

public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> sequence)
{
    return sequence ?? Enumerable.Empty<T>();
}

This function can be combined with all LINQ methods and foreach, not just .Any(), which is why I prefer it over the more specialized helper functions people are proposing here.

新雨望断虹 2024-10-25 06:32:37

我使用

    list.Where (r=>r.value == value).DefaultIfEmpty().First()

如果不匹配,结果将为 null,否则返回对象之一

如果您想要列表,我相信离开 First() 或调用 ToList() 将提供列表或 null。

I use

    list.Where (r=>r.value == value).DefaultIfEmpty().First()

The result will be null if no match, otherwise returns one of the objects

If you wanted the list, I believe leaving of First() or calling ToList() will provide the list or null.

远昼 2024-10-25 06:32:37

it null 将

enter    public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
    {

        try
        {
            return enumerable?.Any() != true;
        }
        catch (Exception)
        {

            return true;
        }
   
    }

在此处返回 true 代码

it null will return true

enter    public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
    {

        try
        {
            return enumerable?.Any() != true;
        }
        catch (Exception)
        {

            return true;
        }
   
    }

code here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文