将一个项目添加到IEnumerable< T>的最佳方法是什么? [英] What's the Best Way to Add One Item to an IEnumerable<T>?

查看:61
本文介绍了将一个项目添加到IEnumerable< T>的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我将一个项目添加到IEnumerable对象的方法:

Here's how I would add one item to an IEnumerable object:

//Some IEnumerable<T> object
IEnumerable<string> arr = new string[] { "ABC", "DEF", "GHI" };

//Add one item
arr = arr.Concat(new string[] { "JKL" });

这很尴尬.我看不到名为ConcatSingle()之类的方法.

This is awkward. I don't see a method called something like ConcatSingle() however.

是否有更干净的方法将单个项目添加到IEnumerable对象?

Is there a cleaner way to add a single item to an IEnumerable object?

推荐答案

不,这与使用内置语言/框架功能一样简洁.

Nope, that's about as concise as you'll get using built-in language/framework features.

如果愿意,您可以始终创建扩展方法:

You could always create an extension method if you prefer:

arr = arr.Append("JKL");
// or
arr = arr.Append("123", "456");
// or
arr = arr.Append("MNO", "PQR", "STU", "VWY", "etc", "...");

// ...

public static class EnumerableExtensions
{
    public static IEnumerable<T> Append<T>(
        this IEnumerable<T> source, params T[] tail)
    {
        return source.Concat(tail);
    }
}

这篇关于将一个项目添加到IEnumerable&lt; T&gt;的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆