Linq casting between types

Is there a better way to pass this list of guide lines to the ends 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 watched:

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

but that doesn't seem like a trick.

Any advice appreciated.

+3
source share
3 answers
guids.Select(x => new Guid(x)).ToList()
+6
source
guids.Cast<Guid>().ToList()

Just trying to pass each list item to Guid. Since you cannot pass the string directly to Guid, this will not work.

However, it's easy to build a Guid from a string, you can do this for each item in the list using a selector:

var guidsAsGuid = guids.Select(x => new Guid(x)).ToList()
+5
source

You can use .Select to implement the correct click:

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

or

IList<string> guidsAsString = ...
var guids  = guidsAsString.Select(g=>new Guid(g));
+1
source

Source: https://habr.com/ru/post/1734225/


All Articles