How to query LinqToTwitter with multiple id's at once?

115 Views Asked by At

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;
    }
}
1

There are 1 best solutions below

5
OfirD On BEST ANSWER

There are several ways to do it, the best would probably be using join. (This seems to get nowhere, because if any ID is not found, an exception is thrown, so that no tweet can be returned).

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;
    }
}