Q:

Linq - choosing item or a default from a list

I have a list of items, for localisation of strings, stored in a SQLite database. I want to retrieve the list, and create a dictionary of items for display purposes using linq. If a localised string does not exist, then I want to return the default language string.
example data
Item    MetaTag     LanguageCode    Text
1       Hello       en              Hello
1       Hello       fr              Bonjour
1       Hello       de              Guten Tag
1       Goodbye     en              Goodbye

so if I want German strings, the dictionary should contain 
1       Hello       de              Guten Tag
1       Goodbye     en              Goodbye

So I have the following code:
public interface ILocalisedItem
{
    int ID { get; set; }
    int ItemId { get; set; }
    string MetaTag { get; set; }
    string LanguageCode { get; set; }
}
public class ItemString : ILocalisedItem
{
    int ID { get; set; }
    int ItemId { get; set; }
    string MetaTag { get; set; }
    string LanguageCode { get; set; }
    string Text {get; set; }
}

public static IDictionary<string, T> GetMetaDataDictionary<T>
    (int ItemId, string DisplayLanguage, string DefaultLanguage)
    where T : ILocalisedItem, new()
{

    IEnumerable<T> metadata = GetMetaData<T>(ItemId);

    ILookup<string, T> _lookup = metadata
        .Where(z => (z.LanguageCode == DisplayLanguage) || (z.LanguageCode == DefaultLanguage))
        .OrderBy(x => (x.LanguageCode == DisplayLanguage) ? 0 : 1)
        .ToLookup(o => o.MetaTag);

    return _lookup.ToDictionary(y => y.Key.ToLower(), y => y.First());
}

This code seems to work, but I think there must be a better way to do this. Can anyone help provide a better solution.

A:

You could consolidate the statement to something along the lines of:
ILookup<string, T> _lookup = metadata
    .Where(z => (z.LanguageCode == DisplayLanguage) || (z.LanguageCode == DefaultLanguage))
    .OrderBy(x => (x.LanguageCode == DisplayLanguage) ? 0 : 1)
    .GroupBy(x => x.MetaTag)
    .ToDictionary(x => x.ToLower(), y => y.First());

It isn't a ton cleaner but avoids the extra lookup conversion. I think your approach of pulling both and filtering is going to be the most efficient way of pulling the data. Going directly to the dictionary should push the first operation back to the database but don't quote me on that. 

