简体   繁体   English

c# 重构与 linq 查询

[英]c# refactoring with linq query

I am trying to improve my linq syntax coding and i was wondering if anyone could show me a better way of writing this code below.Question is taken from leetcode https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ .我正在尝试改进我的 linq 语法编码,我想知道是否有人可以告诉我一个更好的方法来编写下面的代码。问题来自 leetcode https://leetcode.com/problems/kids-with-the-greatest-糖果数/ . Thanks谢谢

        public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
        {
           var kidCandle = candles.Select(x => x+ extraCandies);
           var con = new List<bool>();
            foreach(var kid in kidCandle)
            {
                if (kid >= candles.Max())
                    con.Add(true);
                else
                    con.Add(false);
            }

           return con;
        }

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

Linq also does looping but just a syntacitc sugar, but we can write a Select for the foreach. Linq 也进行循环,但只是一个语法糖,但我们可以为 foreach 编写一个Select So the code:所以代码:

var con = new List<bool>();
foreach(var kid in kidCandle)
{
    if (kid >= candles.Max())
        con.Add(true);
    else
        con.Add(false);
}

can be replaced with:可以替换为:

public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
   var kidCandle = candles.Select(x => x+ extraCandies);
   var maxCandles = candles.Max();
   var con = kidCandle.Select(kid => (kid >= maxCandles)).ToList();
   return con;
}

even the whole method could be written like:甚至整个方法也可以这样写:

public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
    var maxCandles = candles.Max();
    return candles.Select(x => x+ extraCandies)
                 .Select(kid => (kid >= maxCandles)).ToList();
}

Now more simpler:现在更简单了:

public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
   var maxCandles = candles.Max();
   var con = candles.Select(kid => (kid + extraCandies >= maxCandles)).ToList();
   return con;
}

we can even avoid var :我们甚至可以避免var

 public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
 {
     var maxCandles = candles.Max();     
     return candles.Select(kid => (kid + extraCandies >= maxCandles)).ToList();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM