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;
}
}
}
}
}