【问题标题】:filtering a tuple based on item 3 in the tuple根据元组中的第 3 项过滤元组
【发布时间】:2014-04-22 09:27:17
【问题描述】:

我需要从网络服务打印一份使用美元作为货币的国家/地区列表。 数据来自一个名为 country services 的类,其中包含这个元组:

public static IEnumerable<Tuple<string, string, string, string>> GetCountryData()
{
    var countryService = new CountryServiceProxy.country();
    var xmlStringResult = countryService.GetCurrencies();

    var result = new List<Tuple<string, string, string, string>>();

    var xPathDoc = new XPathDocument(new XmlTextReader(new StringReader(xmlStringResult)));
    var navigator = xPathDoc.CreateNavigator();
    var nodes = navigator.Select("//Table");
    var nodeNames = new[] {"Name", "CountryCode", "Currency", "CurrencyCode"};

    while (nodes.MoveNext())
    {
        var nodeValues = new[] {string.Empty, string.Empty, string.Empty, string.Empty};
        for (var i = 0; i < nodeNames.Length; i++)
        {
            var node = nodes.Current.SelectSingleNode(nodeNames[i]);
            if (node != null)
            {
                nodeValues[i] = node.Value;
            }
        }

        result.Add(new Tuple<string, string, string, string>(nodeValues[0], nodeValues[1], nodeValues[2], nodeValues[3]));

    }

    return result;
}

我需要调用该方法并使用它打印出使用美元的国家/地区列表:

private static IEnumerable<Country> Excercise4()
{
    //     var data = CountryService.GetCountryData().Where(x => x.Item3.Contains("Dollar"));
    //    ////var data = CountryService.GetCountryData().Where(x => x.Item3 == "Dollar");
    //    //Console.WriteLine(data);

    return new List<Country>
    {
         new Country("da", "C1", "$", "Dollar"),
         new Country("Country2", "C3", "$", "Dollar")
    };
}

到目前为止,我的方法看起来像这样。我似乎无法弄清楚如何打印出元组,以前没有使用过元组。

我的写法如下:

ConsoleHelper.PrintCountryResults(Excercise4(), "Return a list of Country objects who's currency is Dollar");
ConsoleHelper.Pause(PauseMessage);

控制台助手类看起来像这样:

public static void PrintCountryResults(IEnumerable<Country> results, string title)
{
    PrintHeader(title);
    foreach (var result in results)
    {
        Console.WriteLine("{0, -30}{1, -5}{2, -15}{3, -5}", result.CountryName, result.CountryCode, result.CurrencyName, result.CurrencyCode);
    }
}

任何帮助将不胜感激,因为我说在第一次尝试之前没有使用元组.. 谢谢

【问题讨论】:

  • Tuple 提供对其属性的访问权限,就像Item1Item2ItemN 其中N 指向元组中的类型数,在您的情况下将有 4 . 除此之外,我不确定你的问题是什么。
  • 主要问题是如何使用我在上面发布的命令行帮助程序类将元组打印到列表中,然后打印到命令行中。但从那以后我解决了问题

标签: c# list filter tuples


【解决方案1】:

您可以通过引用 ItemX 属性来过滤元组的属性,其中 X 是您感兴趣的属性的从 1 开始的索引。在这种情况下,如果货币是第三项,则过滤元组看起来像

var countriesUsingDollarAsACurrency = GetCountryData().Where(tuple => tuple.Item3 == "Dollar");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2019-08-03
    相关资源
    最近更新 更多