什麼:
public static IEnumerable<T> ConcatN<T>(this IEnumerable<T> source, IEnumerable<T> source2, int maxSize)
{
if (maxSize == 0)
throw new ArgumentException(
"maxSize cannot be zero", "maxSize");
var sourceCount = source.Count();
if (sourceCount > maxSize)
throw new ArgumentException(
"source has more elements than the given maxSize");
if (sourceCount + source2.Count() < maxSize)
throw new ArgumentOutOfRangeException(
"source and source2 has combined, more elements than the given maxSize");
return source.Concat(source2.Take(maxSize - sourceCount));
}
- 如果項目在
source
數量超過給定的maxSize
,一個異常throwen。
- 如果
source
+ source2
中的項目數少於給定的maxSize
,則會發生異常。
用法:
var number1 = Enumerable.Range(0, 10);
var number2 = Enumerable.Range(100, 10);
var number12 = number1.ConcatN(number2, 15);
Console.WriteLine("Length = {0} | Sum = {1}",
number12.Count(), number12.Sum());
// Output: "Length = 15 | Sum = 555"
來源
2014-02-21 14:09:32
ebb
你從哪裏得到N個元素? –
做一個簡單的循環? – poke