Thursday 20 January 2011

ArrayList and SingleOrDefault

Scenario: I get passed an ArrayList of all LanguageEntity's.

I have in my possession a LanguageEntity.ID and need to retrieve from the ArrayList, LanguageEntity.Description where the ID matches.

Ideally, I want to do this:


LanguageEntity referencedLangEntity = allLanguages.SingleOrDefault(lang => lang.ID == targetLanguageID);
string description = referencedLangEntity.Description;


and be done with it!

However, it appears that SingleOrDefaul does not work with ArrayList's...I would need allLanguages to be a generic list type List.

Converting from the ArrayList to List seems to cumbersome and timely to be worth it.

So instead, I have come up with this solution using Lambda expressions:

var query = from LanguageEntity lang in allLanges
where lang.ISOCode == language.LanguageCodeID
select lang;
string description = query.First().Description;


I hope to find a more elegant solution...any recommendations would be most welcome!

SUGGESTION


It has been suggested that one can convert from the ArrayList to an Array of LanguageEntity objects and then you can call SingleOrDefault:

SingleOrDefault with object property refernces


But that didn't work ( because the ArrayList i had been given was actually full of Hashtables, not LanguageEnity's).

So instead, i've gone with the simplest way possible:

foreach (Hashtable ht in allLangsArrayList)
                    {
                        if (ht["value"].ToString() == language.LanguageCodeID)
                        {
                            table = ht;
                            break;
                        }
                    }

No comments:

Post a Comment