views:

95

answers:

2

What is the best way to localize a collection (IEnumerable)? From the BL I retrieve a collection of entities which still need to localized, I figured I write a method which extends the IEnumerable and returns the localized list.

How can i get the code underneath working? Any ideas? Maybe better options?

public static IEnumerable Localize(this IEnumerable items, CultureInfo cultureInfo)
{
    foreach(string item in items)
    {
        /*Error underneath, cannot assign to item*/
        item = ResourceHelper.GetString(item, cultureInfo);
    }
    return (items);
}
+2  A: 

have you tried something where you yield the item?

public static IEnumerable<string> Localize(this IEnumerable<string> items, CultureInfo culture)
{
    foreach (string item in items)
    {
        yield return ResourceHelper.GetString(item,culture);
    }
}

this won't change any other the items in the collection you are enumerating over, but it will return what you want it to.

Darren Kopp
Correct me if I'm wrong but won't this solution recompute the localization every time you iterate over the enumerable? Sounds like what he wants is a different enumerable collection that has been localized.
tvanfosson
yield is C#s Ninja keyword...nice...!
Codewerks
http://www.lnbogen.com/2008/10/18/TheBeautyOfYieldStatement.aspx
Codewerks
+1  A: 

Simple change to get it to return a new enumerable collection of localized values:

public static IEnumerable<string> Localize(this IEnumerable<string> items, CultureInfo cultureInfo)
{
    List<string> newItems = new List<string>();
    foreach(string item in items)
    {
       newItems.Add( ResourceHelper.GetString(item, cultureInfo) );
    }
    return newItems;
}
tvanfosson