Akzhol
Akzhol

Reputation: 83

Filter array items by a certain string

I am new to C# and I've been trying to make a simple method that is supposed to take a string array and a prefix, then filter the array items by the prefix.

Basically, if I pass an array like string[] data = "A horse, or a HORSE!!!".Split(' '); to it it should return {"horse,","HORSE!!!"} if the prefix = "horse". Naturally, if an empty string prefix is passed, it should return every item. I think I got close to getting it right myself, but now I hit the wall.

I also wanted it to return the ArgumentIsNull exception for when prefix = null. But weirdly it just doesn't want to trigger! I tested and the exception is thrown when there is no foreach loop, but isn't with foreach. Why does it behave like that?

using System;
using System.Collections.Generic;
using System.Linq;

namespace Enumerable
{
    public class EnumerableManipulation
    {
        public IEnumerable<string> GetPrefixItems(IEnumerable<string> data, string prefix)
        {
            if (prefix == null) 
            {
                throw new ArgumentNullException(); 
            } 
            ///Why does this exception never trigger when I pass a null prefix? But it works if there is no foreach.

            foreach (string item in data)
            {
                ///I thought this would do the trick and now I can't figure out why it doesn't work
                if (data.All(prefix.Contains))
                {
                    yield return item;
                }
            }
        }
    }
}

Upvotes: 1

Views: 1502

Answers (2)

Abir Mahmud
Abir Mahmud

Reputation: 135

If you don't need to yield the output then you can use Linq to filter your array like following:

IEnumerable<string> data = "A horse, or a HORSE!!!".Split(' ');
IEnumerable<string> result = data.Where(x => x.Contains("horse"));

Upvotes: 0

Felix Almesberger
Felix Almesberger

Reputation: 901

It is an enumeration. All of your code including the stuff happening before the yield, will only be executed, if you actually enumerate through the result of your function. By calling .ToList() or by a foreach loop.

If you do this:

var result = GetPrefixItems(..., null).ToList() 

It should give you an exception.

Upvotes: 1

Related Questions