Dev
Dev

Reputation: 1826

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

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

Answers (1)

OfirD
OfirD

Reputation: 10490

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

Upvotes: 1

Related Questions