我對C#編程還很陌生,需要一些幫助。模式匹配後在foreach循環中填充列表<T>
我想將我從JSON提要收集的值分配給我自己的類型,其中我定義了將JSON元素放入的某些字段(屬性)的類,以及從RegEx派生的元素模式匹配過程。這將允許我使用LINQ訪問對象,因爲我使用List來保存我的對象。
我的代碼中存在一個foreach循環,用於循環查找每個匹配的RegEx方法。我只對JSON提要中存在匹配的部分感興趣。
所以我自己定義的類是這樣的:
//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; }
}
然後我想在正則表達式來填充列表匹配循環:
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,
};
}
然後,該代碼將繼續提取和排序結果通過Linq到Objects。但編譯器實際上不會讓我創建var tc = new List<TwitterCollection>()
,因爲:'System.Collections.Generic.List'不包含'origURL'的定義...即使我已經定義了它。
它不會標記一個錯誤,如果我只是寫new TwitterCollection
但我怎麼在我的Linq表達式中引用這個?
請幫忙!
你爲什麼使用JSON API?爲什麼不使用XML? – 2010-01-15 18:25:15
JSON的開銷較小(顯然)? 事情是...我已經使用了下面提供的解決方案,但是爲什麼現在無處不在說TwitterCollection ... ???看起來很奇怪 – Alex 2010-01-15 18:28:44