How to map List of classes
// Method to show call usage.
public List<MappedUser> MapListOfUsers(List<User> users)
{
// option 1
List<MappedUser> mappedUsers = users.Select(user => MapSingleUser(user))
.ToList();
// option 2
List<MappedUser> mappedUsers2 =
(from user in users select MapSingleUser(user)).ToList();
}
method to encapsulate mapping itself
private MappedUser MapSingleUser(User user)
{
var mapped = new MappedUser
{
Id = user.Id,
Name = user.Name,
Email = user.Email
};
return mapped;
}
This provides easier and more legible than doing a foreach
to iterate everything.
How to use in async await env
We separate the linq query into Task and Execution. This executes this Task concurrently.
public List<MappedUser> MapListOfUsers(List<User> users)
{
var mapTask = users.Select(async user => { return await MapSingleUser(user); });
List<MappedUser> list = (await Task.WhenAll(mapTask)).ToList();
return list;
}
How to filter list per properties (Where)
var testTask = response.result.hashtags
.AsParallel()
.Where(hashtag => "contentsgroup".Equals(hashtag.hashtagType.ToLower()))
.Select(async hashtag => {
if(hashtag.hashtagType.Equals("contentsgroup"))
{
return await Test(hashtag, msgId, log);
} else
{
return hashtag;
}
});
How to execute query as parallel (AsParallel)
var testTask = response.result.hashtags
.AsParallel()
.Where(hashtag => "contentsgroup".Equals(hashtag.hashtagType.ToLower()))
.Select(async hashtag => { return await Test(hashtag, msgId, log);});