Вот решение псевдокода
for each number in array
if is looking for odd and number is odd
remember position
set is looking for odd to false
if is looking for even and number is even
distance = remembered position - current position
quit loop
I take it you can't just Insert
into the existing list?
Well, you could use new[] {element}.Concat(list)
.
Otherwise, you could write your own extension method:
public static IEnumerable<T> Prepend<T>(
this IEnumerable<T> values, T value) {
yield return value;
foreach (T item in values) {
yield return item;
}
}
...
var singleList = list.Prepend("a");
public static class IEnumerableExtensions
{
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> ie, T item)
{
return new T[] { item }.Concat(ie);
}
}
Вы можете бросить свой собственный:
static IEnumerable<T> Prepend<T>(this IEnumerable<T> seq, T val) {
yield return val;
foreach (T t in seq) {
yield return t;
}
}
И затем использовать его:
IEnumerable<string> singleList = list.Prepend(element);
Также:
IEnumerable<string> items = Enumerable.Repeat(item, 1).Concat(list);
This would do it...
IEnumerable<string> singleList = new[] {element}.Concat(list);
If you wanted the singleList to be a List then...
IEnumerable<string> singleList = new List<string>() {element}.Concat(list);
... works too.
Нет, такой встроенной инструкции, оператора нет, но реализовать такую функцию тривиально:
IEnumerable<T> PrependTo<T>(IEnumerable<T> underlyingEnumerable, params T[] values)
{
foreach(T value in values)
yield return value;
foreach(T value in underlyingEnumerable)
yield return value;
}
IEnumerable<string> singleList = PrependTo(list, element);
Вы даже можете сделать это метод расширения, если версия C # позволяет.