Wednesday, 19 January 2011

Convert string[] to List (string) to List (int)

My method gets passed an array of strings, representing a collection of integer IDs.

Would be most convenient if this were actually a list of integers because i want to update a collection so that it contains only the new IDs returned from client.

So i now do this:

List<int> agenciesToRemove = new List<int>();
List<string> strFreshAgencies = new List<string>(freshAgencyIDs);
List<int> intFreshAgencies = strFreshAgencies.ConvertAll<int>(delegate(string s) { return int.Parse(s); });

foreach (ensShortListSupportAgency staleAgency in this.ensShortListSupportAgencyCollectionByShortListID)
    // Search the FreshAgencies ids for one that matches this staleAgency ID.
    // If NOT found, then it needs to be removed from the ShortListSupportAgency collection
    int foundID = intFreshAgencies.Find(id => id == staleAgency.CodeSupportAgencyID.Value);
    if (foundID == 0)

Instead of doing this:

foreach (ensShortListSupportAgency staleAgency in this.ensShortListSupportAgencyCollectionByShortListID)
bool found = false;
    foreach (string strAgencyID in freshAgencyIDs)
        int freshAgencyID = Convert.ToInt32(strAgencyID);
        if (staleAgency.CodeSupportAgencyID.Value == freshAgencyID)
            found = true;
    if (!found)
        // Cant modify a collection whilst enumerating over it so add the ID to a temp removal collection

But an even sweeter way to get the conversion happening is using lambda:

List<int> intFreshAgencies = strFreshAgencies.ConvertAll<int>(s => int.Parse(s));

Problem with this is when the variable 's', an entry within the strFreshAgencies collection, is an empty string.

So perhaps going back to a delegate here would be worth the sacrifice of elegant code to more robust code:

List<int> intLatestAgencies = strLatestAgencies.ConvertAll<int>
    (delegate(string s)
            int result;
            if (int.TryParse(s, out result))
                return result;
                return 0;

The question then raised is: Will placing '0' into the 'intLatestAgencies' list really be OK???

Most probably what do we do if we can't convert the string to an integer (eg if the string is empty)? What we really want to do is not insert anything in 'intLatestAgencies' list at all...but I don't think ConvertAll is going to be that kind to us!

So we might have to loop through and create the list manually instead:

code here

No comments:

Post a Comment