转换IEnumerable<;字符串>;到ICollection<;字符串>;

本文关键字:gt 字符串 lt ICollection 转换 IEnumerable | 更新日期: 2023-09-27 18:25:18

我将IEnumerable<string>ICollection<string>作为参数传递给方法。在该方法中,我想将一些值连接到ICollection<string>,并将concat调用的返回值重新分配回传入的ICollection<string>。我的问题是,最有效的方法是什么?

无法将源类型'System.Collections.Generic.IEnumerable<string>'转换为目标类型'System.Collections.Generic.ICollection<string>'

void DoSomething(IEnumerable<string> values, ICollection<string> otherValues)
{
    // Ideally, I could chain after the Concat and get my ICollection<string>.
    otherValues = otherValues.Concat(GetConcatValues());
    // Remaining source left out for brevity...
}

我完全理解转换的问题,并且ICollection<string>继承了IEnumerable<string>。此外,我知道.Concat调用返回的是IEnumerable<string>,而不是所需的ICollection<string>

我只是想知道是否有一个单行扩展方法已经存在,它会故意将其转换为我想要的集合?此外,我刚刚意识到我说了IEnumerable<string>ICollection<string>无数次。。。

转换IEnumerable<;字符串>;到ICollection<;字符串>;

由于您必须转换为实现ICollection接口的类之一,因此在IEnumerable<string>上调用ToList即可:

otherValues = otherValues.Concat(GetConcatValues()).ToList();

注意:分配给otherValues在调用方中没有效果,因为它不是通过引用或out参数传递的。假设您正在将一个可修改的集合传递到方法中,您可以这样做来用来自Concat:的数据填充它

foreach(var s in GetConcatValues()) {
    otherValues.Add(s);
}