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. i.e. 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,TOutput>(TInput[], System.Converter<TInput,TOutput>)'
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);
I'm not familiar with ConvertAll, but try using 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.