I'm fairly new to C# programming and need some help.
I am trying to assign values I've gathered from a JSON feed to my own type, a class in which I have defined certain fields (properties) to put the JSON elements into, plus elements that are derived from a RegEx pattern matching process. This will then allow me to access the object using LINQ, as I am using a List to hold my objects.
There is a foreach loop in my code that loops for each match that my RegEx method finds. I am only interested in the parts of the JSON feed where there is a match.
So my own defined class is as such:
//simple field definition class
public class TwitterCollection
{
public string origURL { get; set; }
public string txtDesc { get; set; }
public string imgURL { get; set; }
public string userName { get; set; }
public string createdAt { get; set; }
}
And then I want to populate List in the RegEx Matches loop:
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
var tc = new List<TwitterCollection>()
{
origURL = groups[0].Value.ToString(),
txtDesc = res.text,
imgUrl = res.profile_image_url,
userName = res.from_user_id,
createdAt = res.created_at,
};
}
The code will then go on to extract and sort the results via Linq to Objects. But compiler won't actually let me create my var tc = new List<TwitterCollection>()
because: 'System.Collections.Generic.List' does not contain a definition for 'origURL' ... even though I have defined it.
It does not flag an error if I simply write new TwitterCollection
but then how do I refer to this in my Linq expression later on??
Please help!
You need to instantiate the list outside the loop:
var list = new List<TwitterCollection>();
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
var tc = new TwitterCollection
{
origURL = groups[0].Value.ToString(),
txtDesc = res.text,
imgUrl = res.profile_image_url,
userName = res.from_user_id,
createdAt = res.created_at,
};
list.Add(tc);
}
At the moment, you are trying to create a new list for each element. The actual compilation error is because your object initialiser is for a TwitterCollection
object, not a list of them, but there's no point fixing that with this flaw in the logic anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With