Is there a better way to cast this list of guid strings to guids using linq:
public static IList<Guid> ToGui开发者_JAVA百科dList(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.
guids.Select(x => new Guid(x)).ToList()
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()
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));
精彩评论