Is it better to yield return lookup lists or preload a static list in c#?

I have a simple lookup list that I will use to populate a dropdown in Silverlight. In this example I'm using US States.

I'm trying to figure out if its better to return a static list or use the yield keyword. Of the following two pieces of code, which is the preferred and why?

Version 1: Using yield return

public class States
{
    public static IEnumerable<string> GetNames()
    {
        yield return "Alabama"; 
        yield return "Alaska";
        yield return "Arizona";
        yield return "Arkansas";
        yield return "California";
        yield return "Others ...";
    }
}

Version 2: Return the list

public class States
{
    private static readonly IList<string> _names;

    static States()
    {
        _names = new List<string>() {"Alabama", 
                                     "Alaska",
                                     "Arizona",
                                     "Arkansas",
                                     "California",
                                     "Others ..." };

    }

    public static IList<string> GetNames()
    {
        return _names;
    }
}

The question you need to ask yourself is : "do I want the code that calls GetNames to be able to modify the list ?"

  • If the answer is yes, return a IList , implicitly saying : "read-write"
  • If the answer is no, return a IEnumerable , implicitly saying : "read-only"
  • Anyway, I think you should put the state names in a resource file, rather than hard-coding them (even though that list is unlikely to change in the short term...)

    Here is what I would do :

    public static IEnummerable<string> GetNames()
    {
        foreach(string name in _names) yield return name;
    }
    

    This way you don't directly expose the list to the "outside world"


    I think I'd prefer the list for this. The only advantage the yield method might offer over the List here is to avoid needing to keep all the elements in memory at once, but you're going to do that anyway.


    这可能有助于解释为什么你应该使用V1 http://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/

    链接地址: http://www.djcxy.com/p/53758.html

    上一篇: 动态+ linq编译错误

    下一篇: 在c#中生成返回查找列表或预加载静态列表会更好吗?