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.
Related
Excuse me, a quick question:
I have a list of strings, string are full paths of some files. I would like to get only the filename without the path neither the extension for each string (and to understand lambda more)
Based on the lambda expression in How to bind a List to a DataGridView control? I am trying something like the below:
FilesName = Directory.GetFiles(fbd.SelectedPath).ToList(); // full path
List<string> FilesNameWithoutPath = AllVideosFileNames.ForEach(x => Path.GetFileNameWithoutExtension(x)); // I want only the filename
AllVideosGrid.DataSource = FilesNameWithoutPath.ConvertAll(x => new { Value = x }); // to then bind it with the grid
The error is:
Can not convert void() to List of string
So I want to apply Path.GetFileNameWithoutExtension() for each string in FilesName. And would appreciate any extra description on how Lamba works in this case.
ForEach will execute some code on each item in your list, but will not return anything (see: List<T>.ForEach Method). What you want to do is Select the result of the method (see: Enumerable.Select<TSource, TResult> Method), which would look something like:
List<string> FilesNameWithoutPath = AllVideosFileNames
.Select(x => Path.GetFileNameWithoutExtension(x))
.ToList();
You are using List<T>.ForEach method which takes each element in the list and applies the given function to them, but it doesn't return anything. So what you are doing basically is getting each file name and throwing them away.
What you need is a Select instead of ForEach:
var fileNamesWithoutPath = AllVideosFileNames
.Select(x => Path.GetFileNameWithoutExtension(x))
.ToList();
AllVideosGrid.DataSource = fileNamesWithoutPath;
This will project each item, apply Path.GetFileNameWithoutExtension to them and return the result, then you put that result into a list by ToList.
Note that you can also shorten the Select using a method group without declaring a lambda variable:
.Select(Path.GetFileNameWithoutExtension)
I am reading a collection of strings (of GUID format) from excel and want to store them in database as collection of GUIDs. I am just wondering is there any clean way to convert List<string> to List<Guid> using Linq. I am not interested in looping through.
Either LINQ:
List<Guid> guids = guidStrings.Select(Guid.Parse).ToList();
or List.ConvertAll which is a little bit more efficient because it knows the size:
List<Guid> guids = guidStrings.ConvertAll(Guid.Parse);
Yep
IEnumerable<Guid> guids = guidStrings.Select(x => Guid.Parse(x));
Or as juharr said in their comment below, you can simplify this a little to a "method group":
IEnumerable<Guid> guids = guidStrings.Select(Guid.Parse);
Because C# can work out that the only argument passed-in is the same as the only argument required by Guid.Parse() so the compiler does it for you.
The easiest approach would be to take advantage of the Enumerable.Select() method which can map each of your individual strings to a corresponding Guid :
// This will parse each string present in your strings collection to its cooresponding guid
var guids = strings.Select(Guid.Parse);
This is how it is done:
IEnumerable<string> guidStrings = ..... // GUID-compatible strigns
List<Guid> guids = guidStrings.Select(s => new Guid(s)).ToList();
I have the below
var deptRecs= DepartmentRecords; //it is of type IEnumerable<Department>
var deptIDs= new string[] { "1", "2" };
var result = deptIDs.Intersect(?????)
I want to figure out the common department id's. What will sit in the predicate of Intersect?
Use the following instead of Intersect:
deptRecs.Where(d=>deptIDs.Contains(d.DeptId))
For intersect you need same types of entities.
Hope it helps...
Thanks.
You can use Where with Contains instead of Intersect:
var result = deptRecs.Where(x => deptIDs.Contains(x.Id)).ToList();
Assuming Id property of int type on Department class it is enough to filter them with Contains() operation
var result = deptRecs.Where(r=>deptIDs.Contains(r.Id.ToString()))
The Enumerable.Intersect expects argument of the same type. Thus, to perform a set intersection, as you are trying to pass in an array of string, an example can be
DepartmentRecords.Select(i=>i.DepartmentName).Intersect(deptIDs);
I am assuming you have a DepartmentName property of type string. Performing a selection operation returns an IEnumerable<string>. Then I am passing in the array, which will return the set intersection of the two enumerables.
Please help me i am integrating bing app in my application. I have got this error "system collection generic.iList<long> to long[]". Below is my AddCampaigns function:
static long[] AddCampaigns(long accountId, Campaign[] campaigns)
{
var request = new AddCampaignsRequest
{
// Set the header information.
UserName = *******,
Password = *******,
DeveloperToken = DeveloperToken,
CustomerAccountId = accountId.ToString(CultureInfo.InvariantCulture),
AuthenticationToken = "EwB4AnhlBAAUlZly8ML8fhDf5bGNDempXPXcgIkAAR6FFH6GZgnGlMCKP+G72LRhOQ+NSiYSSxHSpLWP8XZ/DbYJLgSHHUPFyswjNewclBJFuG/hTZyrZ5m8zTKqW1lSSPL76H5Wfn5CJUG3PWwEm6yl4TdqXlekTcEbyZgXxCNs+IwXwzaaEuxWeNAGl2Fdw/AVYg1DpcAgVZ8h1up833SizwHaBx1HSbDwMxJQOdQWy0wuBuCzIFoXS4TJchHQwrNhRE1fkJNqGoqpmNPSIU8FnOreEHpmtRq84xSorI5GJ2NytwJA2OiBxgGxd15b4jJ6UpSr1gbRNAwAQ6lfp2hteKze/c7RL49evxDXfmVF2KDhySQGRfIk5I3V7Y4DZgAACG16WwzKc/17SAFUXSSUZqD3WEdQmIKaJmysvsUi0hWNf1m9mmq6j8giqiUiscMj87WN+lBRX5WB8uRNHcFfvxKuNvJL7+A0OY7NvzKT43ALcK9dxPF9f00dmVNdNTv1omGzv3SrmulkX7rJxA2rMg72LA69qdrc3zNruWG0IOAghElJT6UnLaECoPJkG3zQtYD5YJjLXxOdjOgucL8hZjKGaJ7uL/xvZRve8hStQdVVffmnqkmILjkrpj30o+61Tw7ppiyw4c/Felo9V2/19y/Uwyg0LA42bHmx2E7WIz9W1JJsBq5ptEwwrz7aho5RKWuh6WOmBtbvwcC4Z+FF6y0KYUjjUuPV6zJ4r3aeX9xE6ZhALQt+JCPlsWRqvglY7TbdB7ELjrAvgz0emrRSsO0PMQRA/IuJjP/VlxZ52Kquv4f03esn92KLIYd9CyFFHFD+XgE=",
// Set the request information.
AccountId = accountId,
Campaigns = campaigns
};
return _service.AddCampaigns(request).CampaignIds;
}
Thanks in advance.
Assuming from your title that CampaignIds is a IList<long> then you can simply use the Linq's ToArray() to fix the issue
using System.Linq;
//...
return _service.AddCampaigns(request).CampaignIds.ToArray();
If CampaignIds needs any sort of translation, add a .Select() before ToArray()
//...
return _service.AddCampaigns(request).CampaignIds
.Select(id => /** Some Translation work **/ )
.ToArray();
You should also carefully consider the use of Long[] against a sinple IEnumerable<long> depending on usage - there is some overhead to using .ToArray that could be avoided if you don't need array-specific functionality out of the result.
Use the ToArray() LINQ method available on IEnumerable<T>.
You must convert list to array with
.ToArray()
method of List object.
Suggestion:
By the way, are you sure you really need an array or a list or IEnumerable?
I have a class PlaceInfo that contains a private field of type Result. in the constructor of PlaceInfo i take parameter of type Result.
Now my JsonConvert.DeserializeObject<SearchFind>(JsonData); statement provides me Result[] in res.Results.
I have to construct a List<PlaceInfo>.
The simplest and thumb logical way is given below (that i am using currently).
foreach (var serverPlace in res.Results)
lstPlaces.Add(new PlaceInfo(serverPlace));
Can anyone suggest me advanced constructs?
You can use LINQ:
lstPlaces = res.Results.Select(x => new PlaceInfo(x)).ToList();
remember to add using System.Linq at the top of the file.
You could use the Linq Select and ToList method
Result[] results = ...
List<PlaceInfo> places = results.Select(x => new PlaceInfo(x)).ToList();
The Select method is a projection, applying the given function to all the elements in your array. The ToList method takes the resultant IEnumerable and creates a List.