如何在 C# 中填充和返回元组列表

本文关键字:返回 元组 列表 填充 | 更新日期: 2023-09-27 18:19:15

关于如何从方法重新调整元组,我有一个很好的建议:

如何从 C# 中的方法返回多个值

现在我意识到我的代码不仅产生两个值,还生成一个 IEnumerable<>。 这是我到目前为止的代码,其中结果包含一个 IEnumerable 我猜一个包含注释和标题的匿名对象。我不太确定如何将数据放入元组,也不确定如何将其从变量 myList 中取出。我可以在myList上做一个foreach吗?

    public static IEnumerable< Tuple<string, string> > GetType6()
    {
        var result =
            from entry in feed.Descendants(a + "entry")
            let notes = properties.Element(d + "Notes")
            let title = properties.Element(d + "Title")
        // Here I am not sure how to get the information into the Tuple 
        //  
    }
    var myList = GetType6();

如何在 C# 中填充和返回元组列表

您可以使用

constructor

public static IEnumerable<Tuple<string, string>> GetType6()
{
    return
        from entry in feed.Descendants(a + "entry")
        let notes = properties.Element(d + "Notes")
        let title = properties.Element(d + "Title")
        select new Tuple<string, string>(notes.Value, title.Value);
}

但老实说,为了使代码更具可读性和使用模型,您需要付出什么代价:

public class Item
{
    public string Notes { get; set; }
    public string Title { get; set; }
}

然后:

public static IEnumerable<Item> GetType6()
{
    return 
        from entry in feed.Descendants(a + "entry")
        let notes = properties.Element(d + "Notes")
        let title = properties.Element(d + "Title")
        select new Item
        {
            Notes = notes.Value, 
            Title = title.Value,
        };
}

恕我直言,操作元组会使代码非常不可读。当你开始写那些result.Item1result.Item2,...,result.Item156事情变得可怕。如果你有result.Titleresult.Notes,...,那就更清楚了,不是吗?