Ian*_*ose 10 .net c# linq ienumerable
必须有一个很好的标准方法来做到这一点,但是我工作的每个项目我都必须编写自己的统一方法,或者创建一个内联数组等.
(我希望这会很快被关闭作为一个问题的副本,并对此有一些很好的答案)
Jon*_*eet 19
一个简单的方法:
var singleElementSequence = Enumerable.Repeat(value, 1);
Run Code Online (Sandbox Code Playgroud)
或者你可以在无约束的泛型类型上编写自己的扩展方法(通常是一个坏主意,诚然......谨慎使用):
public static IEnumerable<T> ToSingleElementSequence<T>(this T item)
{
yield return item;
}
Run Code Online (Sandbox Code Playgroud)
用于:
IEnumerable<String> sequence = "foo".ToSingleElementSequence();
Run Code Online (Sandbox Code Playgroud)
我想我会Enumerable.Repeat优先使用虽然:)
小智 6
最短的方法是
new T[]{value}
Run Code Online (Sandbox Code Playgroud)
编辑刚刚想到在 LINQ 中提到一些我最喜欢的设备:
internal static IEnumerable<T> Concat<T>(params T[] objs)
{
return objs;
}
internal static IEnumerable<T> Concat<T>(this IEnumerable<T> e, params T[] objs)
{
return e.Concat(objs);
}
internal static IEnumerable<T> Concat<T>(this IEnumerable<T> e, params IEnumerable<T>[] seqs)
{
foreach (T t in e) yield return t;
foreach (var seq in seqs)
foreach (T t in seq) yield return t;
}
// this allows you to
var e1 = Concat(1,2,3); // 1,2,3
var e2 = e1.Concat(4,5,6); // 1,2,3,4,5,6,
var e3 = e2.Concat(e2, e1, Concat(42)); // 1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,42
Run Code Online (Sandbox Code Playgroud)
以任何方式、形状或形式定义文字列表都非常方便
另一种简单的方法:
IEnumerable<int> = new [] {42};
Run Code Online (Sandbox Code Playgroud)
还有一个简单的方法:
internal static IEnumerable<T> Enumerable<T>(this T obj)
{
yield return obj;
}
//
var enumerable = 42.Enumerable();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4943 次 |
| 最近记录: |