How can I create a singleton IEnumerable?

后端 未结 3 1305
天命终不由人
天命终不由人 2021-01-17 11:05

Does C# offer some nice method to cast a single entity of type T to IEnumerable?

The only way I can think of is something like:

相关标签:
3条回答
  • 2021-01-17 11:22

    I use

    Enumerable.Repeat(entity, 1);
    
    0 讨论(0)
  • 2021-01-17 11:28

    Your call to AsEnumerable() is unnecessary. AsEnumerable is usually used in cases where the target object implements IQueryable<T> but you want to force it to use LINQ-to-Objects (when doing client-side filtering on a LINQ-compatible ORM, for example). Since List<T> implements IEnumerable<T> but not IQueryable<T>, there's no need for it.

    Anyway, you could also create a single-element array with your item;

    IEnumerable<T> enumerable = new[] { t };
    

    Or Enumerable.Repeat

    IEnumerable<T> enumerable = Enumerable.Repeat(t, 1);
    
    0 讨论(0)
  • 2021-01-17 11:39
    var entity = new T();
    var singleton = Enumerable.Repeat(entity, 1);
    

    (Although I'd probably just do var singleton = new[] { entity }; in most situations, especially if it was only for private use.)

    0 讨论(0)
提交回复
热议问题