简体   繁体   中英

What is the syntax to create an anonymous instance of IEnumerable in C#?

I have a function which takes an argument of IEnumerable. Let's call it:

Iter(IEnumerable<string> list)

I have a single string that I would like to pass into the function. Is there a way to do it without actually creating some object that implements IEnumerable? It seems like I should be able to use a lambda instead, like :

string thing1 = "Frank";
Iter( () => { yield return thing1 };);

To reiterate, no pun intended, I was wondering if there was a way to use an anonymous function/lambda so I don't have to create a instance of a container.

What about:

Iter(new [] {thing1});

Since your parameter is IEnumerable<string> , you can pass an array or List<string> .

对于一个字符串,还有另一种方式:

Iter(Enumerable.Repeat<string>("thing1", 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM