Reputation: 31
I believe i'm missing something simple here, but i just can't figure it out. Any kind of help would be much appreciated.
The problem:
The results that end up in the resultsWithMedia
array only contain results that were matched against the first item in mediaTypesList
. I've tried using Exists()
, Find()
and Contains()
, but with no luck. I get the same kind of behavior each time.
For example: if mediaTypesList
contains {"video", "link", "photo"}
values, the resultsWithMedia
will only hold results that are of type video
.
What i'm trying to achieve is to have resultsWithMedia
hold the values who's type
matches any of the values in mediaTypesList
.
The code:
public void GetPostsWithMedia(string from, string before, string mediaTypes)
{
// ... some variable declarations
List<string> mediaTypesList = new List<string>();
if (!string.IsNullOrEmpty(mediaTypes))
{
var list = mediaTypes.Split(',');
foreach (var type in list)
{
mediaTypesList.Add(type);
}
}
// ... some more code
// Note: r.Data is a Dictionary that contains strings as it's values
var resultsWithMedia = (from r in response.Results
where r.Data.ContainsKey("Type") && mediaTypesList.Exists(t => t == r.Data["Type"])
select new
{
// ... different variables
}).ToArray();
}
}
Upvotes: 1
Views: 139
Reputation: 3582
I've rewritted your code a bit.
var mediaTypesList = mediaTypes.Split(',').Select(e => e.Trim()).ToList();
var resultsWithMedia = response.Results.Data.Where(e => e.ContainsKey("Type") && mediaTypesList.Contains(e["Type"]))
.Select(a => new {
// ... different variables
}).ToArray();
It looks simpler for me.
Upvotes: 1
Reputation: 236208
You can get results with media in one query:
var query = from r in response.Results.Where(x => x.Data.ContainsKey("Type"))
join m in mediaTypes.Split(',')
on r.Data["Type"] equals m
select new {
...
};
If you need case-insensitive comparison for media type and data, apply ToLower(): on r.Data["Type"].ToLower() equals m.ToLower()
. Also consider to apply m.Trim()
if there is empty space in media type name after splitting string (as Euphoric suggested).
Upvotes: 1
Reputation: 1517
If I understand you correctly you want to match by first element. Enumerable.First() will do the trick:
var resultsWithMedia = (from r in response.Results
where r.Data.ContainsKey("Type") &&
mediaTypesList.First(t => t == r.Data["Type"])
select new
{
// ... different variables
}).ToArray();
Upvotes: -1
Reputation: 12849
Check spaces in mediaTypes
before and after ,
Preferably change
mediaTypesList.Add(type.Trim());
Upvotes: 0