2

メソッドからタプルを返す方法について、良い提案がありました。

C# のメソッドから複数の値を返すにはどうすればよいですか?

ここで、コードが 2 つの値だけでなく IEnumerable< > を生成することに気付きました。ここまでの私のコードは、result に 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();
4

1 に答える 1

15

次を使用できます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.Item1それらを書き始めるresult.Item2と、result.Item156事態は恐ろしくなります。result.Titleresult.Notes、 ...があれば、はるかに明確になりますね。

于 2013-06-21T08:47:29.653 に答える