.net, C# tip, Clean Code

C# tip – use the yield keyword to clean up your code

I’ve recently needed to convert from one list of objects to another – specifically, I have a ViewModel containing a custom generic List<User> of users, and to display on my view, I needed to convert this to List<SelectListItem>.

This is a very simple operation:

private static IEnumerable<SelectListItem> ConvertListItemsToSelectList<TList>(IEnumerable<User> users, int valueToMarkAsSelected)
{
    var selectList = new List<SelectListItem>();
 
    foreach (var user in users)
    {
        selectList.Add(
            new SelectListItem {
                Value = user.Id.ToString(),
                Text = user.Name,
                Selected = (user.Id == valueToMarkAsSelected) 
        });
    }
 
    return selectList;
}

I’m not sure that I like the explicit declaration of the List<SelectListItem> at the top of the method. Fortunately, the yield keyword makes this unnecessary.

Yield removes the need to have an explicit declaration of an object to hold the state of an enumeration. So instead of declaring the List<SelectListItem> at the top of my method, I can just use the code below.

private static IEnumerable<SelectListItem> ConvertListItemsToSelectList<TList>(IEnumerable<User> users, int valueToMarkAsSelected)
{
    foreach (var user in users)
    {
        yield return new SelectListItem {
            Value = user.Id.ToString(),
            Text = user.Name,
            Selected = (user.Id == valueToMarkAsSelected) 
        };
    }
}

It’s a small change – but the code’s a little cleaner.

You can read more about the yield keyword on MSDN here.