问题描述:

I am trying to write a one liner code for the following code:

if (a.Count() == n)

{

return a;

}

else if (a.Count() > n)

{

Array.Resize(ref a, n);

return a;

}

else

{

return a.Concat(Enumerable.Repeat(0, n - a.Count())).ToArray();

}

I have tried this so far:

return a.Count() == n ? a :

(a.Count() > n ? Array.Resize(ref a, n) :

a.Concat(Enumerable.Repeat(0, n - a.Count())).ToArray());

But as you can see it won't compile I can not figure out a way to replace the following code with one liner:

Array.Resize(ref a, n);

return a;

Any help will be appreciated. Thanks.

网友答案:
return a.Concat(Enumerable.Repeat(0,n)).Take(n).ToArray();

or

Array.Resize(ref a, n); return a;
网友答案:

How about using Take method instead of Array.Resize:

return a.Count() == n ? a :
 (a.Count() > n ? a.Take(n).ToArray() : 
  a.Concat(Enumerable.Repeat(0, n - a.Count())).ToArray());
相关阅读:
Top