简体   繁体   中英

how to convert list of strings to list of guids

I have following line of code which creates an list of strings.

List<string> tstIdss = model.Ids.Where(x => x.Contains(entityId)).Select(x => x.Split('_').First()).ToList();

I need to convert it into list of Guids. ie List<Guid> PermissionIds.

model.PermissionIds= Array.ConvertAll(tstIdss , x => Guid.Parse(x));

I tried the above way but getting the following error. model.PermissionIds is implemented as following in my model class.

public List<Guid> PermissionIds { get; set; }

Error 3

The type arguments for method 'System.Array.ConvertAll(TInput[], System.Converter)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

You can use Linq's Select and ToList methods:

model.PermissionIds = tstIdss.Select(Guid.Parse).ToList();

Or you can use the List<T>.ConvertAll method:

model.PermissionIds = tstIdss.ConvertAll(Guid.Parse);

我不熟悉ConvertAll ,但尝试使用Select

model.PermissionIds = tstIdss.Select(s=>Guid.Parse(s)).ToList();

I have following line of code which creates an list of strings. I need to convert it into list of Guids.

If your list of strings is safe to parse as Guids, I recommend the answer from @Thomas Leveque.

If your list of strings may contain some non-guids, it is safer to use a TryParse as follows:

Guid bucket = Guid.Empty;
model.PermissionIds = tstIdss.Where(x => Guid.TryParse(x, out bucket)).Select(x => bucket).ToList();

The Where clause will filter out any string which can't be formatted as a Guid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM