简体   繁体   中英

How can I populate and return a list of tuples in C#

I had a good suggestion on how to retun a tuple from a method:

How can I return more than one value from a method in C#

Now I realize that my code produces not just two values but an IEnumerable< >. Here's my code so far where result contains an IEnumerable of I guess an anonymous object containing notes and title. I am not quite sure how to put the data into the tuple and not sure how to get it out of the variable myList. Can I do a foreach over myList ?

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

You could use the 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);
}

But honestly what would cost you to make your code more readable and work with models:

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

and then:

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

Manipulating tuples IMHO makes the code very unreadable. When you start writing those result.Item1 , result.Item2 , ..., result.Item156 things become horrible. It would be far more clear if you had result.Title , result.Notes , ..., wouldn't it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM