Home > Enterprise >  How to return IEnumerable?
How to return IEnumerable?

Time:07-26

I am still learning the basics of C# and found a task where you have to implement the method below, it is supposed to return the same sequence of strings but uppercase, and I assume by sequence it means an array.

But I am also somehow supposed to use IEnumerable for this.

I thought IEnumerable was an interface, how is it a type and a parameter in that method I am supposed to add logic into?

I searched and found that return type IEnumerable means it has to return something that can implement IEnumerable, but the parameters still confuse me, how do I use them to return uppercase? Do I use a foreach ?

using System;
using System.Collections.Generic;

namespace EnumerableTask
{
    public class EnumerableManipulation
    {
        /// <summary> Transforms all strings to upper case.</summary>
        /// <param name="data">Source string sequence.</param>

        public IEnumerable<string> GetUppercaseStrings(IEnumerable<string> data)
        {

        }
}

CodePudding user response:

You can use Linq Select() which would return an IEnumerable. ie:

public IEnumerable<string> GetUppercaseStrings(IEnumerable<string> data)
        {
          return data.Select(d => d.ToUpper());
        }

EDIT: You can check Linq documentation or my blog starting from the oldest post (Feb 2009) at:

FoxSharp

CodePudding user response:

You can also use foreach and yield:

public IEnumerable<string> GetUppercaseStrings(IEnumerable<string> data)
{
  foreach (var item in data) 
    yield return item?.ToUpper();
}

CodePudding user response:

IEnumerable is a generic interface. It represents a collection of objects of type T. In your case, data is a collection of string.

To iterate through the 'data' and acccess the elements one after the others, there is several possibilities.

GetEnumerator()

GetEnumerator gives you a way to iterate through the enumerable. enumerator.Current allows you to access the current element and enumerator.MoveNext() gives you a way to move to the next element in the IEnumerable<T>. At first use call MoveNext() method to place the enumerator at the first element of the IEnumerable<T>. While there is elements to iterate on MoveNext() will return true. When the end is reached MoveNext() returns false.

IEnumerator enumerator = data.GetEnumerator();
while(enumerator.MoveNext())
{
    string text = data.Current;
    /* Do something */
}

foreach

It takes care of all the complexity of the enumerator process.

foreach(string text in data)
{
    /* Do something */
}
  • Related