gpt4 book ai didi

c# - 模式匹配后在 foreach 循环中填充 List

转载 作者:太空狗 更新时间:2023-10-29 22:15:15 25 4
gpt4 key购买 nike

我是 C# 编程的新手,需要一些帮助。

我正在尝试将从 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; }
}

然后我想在 RegEx 匹配循环中填充列表:

    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 to Objects 继续提取和排序结果。但是编译器实际上不会让我创建我的 var tc = new List<TwitterCollection>()因为:“System.Collections.Generic.List”不包含“origURL”的定义......即使我已经定义了它。

如果我简单地写 new TwitterCollection 它不会标记错误但是我以后如何在我的 Linq 表达式中引用它??

请帮忙!

最佳答案

您需要在循环外实例化列表:

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

此刻,您正在尝试为每个元素创建一个新列表。实际的编译错误是因为您的对象初始化程序是针对 TwitterCollection 对象的,而不是它们的列表,但是无论如何都没有必要用逻辑中的这个缺陷来修复它。

关于c# - 模式匹配后在 foreach 循环中填充 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2073776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com