Convert a Collection of Strings into Collection of GUID - c#

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();

Related

I want to check whether items in a list are valid Guids or not. If not valid then replace string with Guid default

I am getting a list of values which contains Guids and strings. But I need only Guids and have to replace string values with default guid value. Can you please suggest how to do that?
var Value=abc.where(n=>n.userId).select(n=>n.userId);
Thanks
I suppose you have a List<string> that you want to transform in a list of Guid.
If this is the case the answer is simply
var newList = abc.Select(c => Guid.TryParse(c, out Guid guid) ? guid : default(Guid));
If you don't want the invalid guids then
var newList = abc.Where(c => Guid.TryParse(c, out _)).Select(x => new Guid(x));

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. 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.

convert type "system collection generic.iList<long> to long[]"

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?

Select String that is not a property of another object

I am writing code that will select string keys from an array ApiIds that are not property ApiId of results objects.
I wrote the following code, but it looks redundant to me, is there a way to combine this into one statement and not convert a HashSet of objects into another HashSet of Strings?
var resultsCached = new HashSet<string>(results.Select(x => x.ApiId));
var missingResults = apiIds.Select(x => !resultsCached.Contains(x));
Thanks.
Except will give you the items that aren't in the other collection:
var missingResults = apiIds.Except(results.Select(x => x.ApiId));
Another efficient O(n) approach is to use HashSet.ExceptWith which removes all elements from the set which are in the second sequence:
HashSet<string> apiIdSet = new HashSet<string>(apiIds);
apiIdSet.ExceptWith(results.Select(x => x.ApiId));
The set contains only strings which are not in results now.

C# Array, How to make data in an array distinct from each other?

C# Array, How to make data in an array distinct from each other?
For example
string[] a = {"a","b","a","c","b","b","c","a"};
how to get
string[]b = {"a","b","c"}
Easiest way is the LINQ Distinct() command :
var b = a.Distinct().ToArray();
You might want to consider using a Set instead of an array. Sets can't contain duplicates so adding the second "a" would have no effect. That way your collection of characters will always contain no duplicates and you won't have to do any post processing on it.
var list = new HashSet<string> { };
list.Add("a");
list.Add("a");
var countItems = list.Count(); //in this case countItems=1
An array, which you start with, is IEnumerable<T>. IEnumerable<T> has a Distinct() method which can be used to manipulate the list into its distinct values
var distinctList = list.Distinct();
Finally,IEnumerable<T> has a ToArray() method:
var b = distinctList.ToArray();
I think using c# Dictionary is the better way and I can sort by value using LINQ

Categories