views:

121

answers:

3

Is there a better way to cast this list of guid strings to guids using linq:

public static IList<Guid> ToGuidList(this IList<string> guids)
    {
        IList<Guid> guidList = new List<Guid>();
        foreach(var item in guids)
        {
            guidList.Add(new Guid(item));
        }
        return guidList;
    }

I looked at:

guids.Cast<Guid>().ToList()

but that didn't seem to be the trick.

Any tips appreciated.

+5  A: 
guids.Select(x => new Guid(x)).ToList()
leppie
+1  A: 

You just can use the .Select to implement a proper cast:

var guids = from stringGuid in dataSource
            select new Guid(stringGuid)

or

IList<string> guidsAsString = ...
var guids  = guidsAsString.Select(g=>new Guid(g));
Gamlor
Too much WOW for you? It's `Guid`, not `Guild` ;p
leppie
Oups, =D. Fixed it. No I've never played WoW.
Gamlor
+4  A: 
guids.Cast<Guid>.ToList()

Just attempts to cast each element of the list to a Guid. Since you can't directly cast a string to a Guid, this fails.

However, it's easy to construct a Guid from a string, you can do so for each element in the list using a selector:

var guidsAsGuid = guids.Select(x => new Guid(x)).ToList()
Johannes Rudolph
thanks for the explanation
Chev