开发者

Best way to do a lookup based on ID, I dont want to update the model. I am drawing a blank?

I am drawing a blank here.. I am using MVC and my model doesn’t have the Value Name, it just has the ID.

The problem is with ‘itm.DegreeTypeId’ it is just an int. But I need to match it up with a string name.. so DegreeTypeId 1 = Associates Degree, 2 = Bachelor, 3 = MBA etc.

I don’t want to update the model to have the name, but instead to a quick lookup. What’s the best way to proceed here? I know I can create a method and have it return the string based on a number but there has to be a better cleaner way.

        string education = string.Empty;
        int eduCount = 0;
        foreach (var itm in candidate.Educations)
        {
            if (eduCount > 0) education += "<br><br>";
            education += string.Format("<b>{0}</b><br>{1} {2}<br>{3}Graduated: {4}<br>",
                                      itm.DegreeTypeId,
                                      itm.InstitutionName,
                                      i开发者_如何学编程tm.InstitutionLocation,
                                      itm.GraduatedOn.HasValue
                                          ? string.Format("{0:MMMM yyyy}", itm.GraduatedOn.Value)
                                          : string.Empty);
            eduCount++;
        }


Try using a Dictionary

static readonly Dictionary<int, string> Degrees = new Dictionary<int, string>() {
    {1, "Associates Degree"},
    {2, "Bachelor"},
    {3, "MBA"},
    ...
};

So the relevant snippet looks like this:

education += string.Format("<b>{0}</b><br>{1} {2}<br>{3}Graduated: {4}<br>",
                                  Degrees(itm.DegreeTypeId),
                                  ...


It's not entirely clear what you're after, but a Dictionary<int, string> could work (or the reverse if you're trying to look things up the other way). Even a string[] could be a simple solution for int to string conversion:

static readonly string[] DegreeTypeNames = { null, // Unused
    "Associates Degree",
    "Bachelor",
    "MBA"
};

That's useful (and performs really well) if you've got a lot of consecutive values, but if they're not all consecutive, the dictionary approach would be better.

If you need to refer to these IDs in code, you should potentially consider using an enum.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜