【问题标题】:Using Linq to replace foreach statement使用 Linq 替换 foreach 语句
【发布时间】:2014-05-28 17:10:50
【问题描述】:

我对在线 linq 的解释有点困惑,所以我想我会做一个线程。

我想用 linq 语句替换我的 foreach 语句,因为我确信做这样的小事情会让我的程序更好。

我想使用 LINQ 的示例:

 public bool CheckForAccount(int accountID)
        {
            bool status = false;

            foreach (AccountHolders accountHolder in AccountHoldersList)
            {
                if (accountHolder.AccountNumber == accountID)
                {
                    status = true;
                    break;
                }
            }
            return status;
        }

请您也解释一下它是如何工作的,以便我了解您在做什么。

提前致谢!

【问题讨论】:

    标签: c# linq for-loop each


    【解决方案1】:

    所以最简洁的陈述可能是:

    public bool CheckForAccount(int accountId)
    {
        return this.AccountHolderList.Any(x => x.AccountNumber == accountId);
    }
    

    英文是这样说的

    检查AccountHolderList 以了解AccountNumber 属性等于accountId任何 种情况。如果有则返回true,否则返回false。

    【讨论】:

    • 你快了一秒 :) +1
    • 你能解释一下你的代码在说什么吗?提前致谢
    • @user3245390 已更新以包含代码描述。虽然从代码中应该很明显:)
    • 好吧,我的现在也可以工作了..:P,但是很多反对票得到了..:(
    • 我不知道 any() 方法及其工作原理,今天从您的回答中学到了新东西..@dav_i
    【解决方案2】:

    两个

    AccountHolderList.Any(x => x.AccountNumber == accountId);
    

    AccountHoldersList.Exists(p => p.AccountNumber == accountId);
    

    工作同样出色。以下是对差异的更深入解释: Linq .Any VS .Exists - Whats the difference?

    你也可以这样用:

      var match = AccountHolderList.FirstOrDefault(x => x.AccountNumber == accountId);
      return match != null ? true : false;
    

    如果您还想获得对匹配项的引用。这工作假设 accountId 是唯一的

    【讨论】:

    • return match != null ? true : false; 可以只替换为return match != null;。它当前读取“如果匹配不等于null返回true返回true否则返回false”
    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多