Reputation: 1826
I am using the linqtotwitter function below to get statuses by ID and it works as expected. But I was wondering if there was a way to only call this function once(by passing the collection of id's to the query and the function would return a collection). Because the way I am currently getting statuses by looping through the collection of Id's and call GetTweetByKey
each time.
C#:
public async Task<Status> GetTweetByKey(string key, StatusType statusType)
{
try
{
return await (
from tweet in _twitterContext.Status
where tweet.Type == statusType &&
tweet.ID == Convert.ToUInt64(key) &&
tweet.TweetMode == TweetMode.Extended &&
tweet.IncludeEntities == true
select tweet).FirstOrDefaultAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
Upvotes: 1
Views: 132
Reputation: 10490
There are several ways to do it, the best would probably be using (This seems to get nowhere, because if any ID is not found, an exception is thrown, so that no tweet can be returned).join
.
Try wrapping your original code with:
public async Task<List<Status>> GetTweetByKeys(string[] keys, StatusType statusType)
{
var tasks = keys.Select(key => GetTweetByKey(key, statusType)).ToArray();
var results = await Task.WhenAll(tasks);
return results.ToList();
}
public async Task<Status> GetTweetByKey(string key, StatusType statusType)
{
try
{
return await (
from tweet in _twitterContext.Status
where tweet.Type == statusType &&
tweet.ID == Convert.ToUInt64(key) &&
tweet.TweetMode == TweetMode.Extended &&
tweet.IncludeEntities == true
select tweet).FirstOrDefaultAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
Upvotes: 1