简体   繁体   English

如何使用C#和XML进行有效计数?

[英]How to count efficiently using C# and XML?

I have a product database in XML. 我有一个XML产品数据库。 For each product I have its width W, height H and price P. 对于每种产品,我都有其宽度W,高度H和价格P。

Given a product with W, H and P, I want to count the number of products with width less than W, and separate counts for those with height < H and those with price < P. Meaning 3 separate and independent numbers resulting from counting. 给定一个具有W,H和P的产品,我要计算宽度小于W的产品数量,并分别对高度<H和价格<P的产品进行计数。这意味着从计数中得出3个独立的数字。

What is an efficient way to do so using C#? 使用C#的有效方法是什么? Obviously, I want to go through each element in the XML file only once. 显然,我只想遍历XML文件中的每个元素。

XML file is made up of following nodes and has been read into an XDocument object: XML文件由以下节点组成,并且已被读入XDocument对象:

<product><name>abc</name><W>7</W><H>3</H><P>40</P></product>

Something like this would work 这样的事情会起作用

  XDocument doc = XDocument.Parse(xml);

  int heightCount = 0;
  int widthCount = 0;
  int priceCount = 0;

  int heightThreshold = 3;
  int widthThreshold = 1;
  int priceThreshold = 1;

  foreach (var product in doc.Descendants("product"))
  {
    int height = Convert.ToInt32(product.Element("H").Value);
    int width = Convert.ToInt32(product.Element("W").Value);
    int price = Convert.ToInt32(product.Element("P").Value);

    if (height < heightThreshold)
    {
      heightCount++;
    }

    if (width < widthThreshold)
    {
      widthCount++;
    }

    if (price < priceThreshold)
    {
      priceCount++;
    }       
  }

This has no safeguards though, so if your product element does not contain an integer value for each of the H,W and P elements (or one of these elements does not exists), it will break. 但是,这没有任何保障措施,因此,如果您的product元素不包含每个H,W和P元素的整数值(或不存在这些元素之一),它将损坏。 You'd need to add some null and conversion checking. 您需要添加一些null和转换检查。

var doc=XDocument.Parse(@"
    <products>
        <product>
            <name>abc</name>
            <W>7</W>
            <H>3</H>
            <P>40</P>
        </product>
        <product>
            <name>abc</name>
            <W>5</W>
            <H>3</H>
            <P>40</P>
        </product>
        <product>
            <name>abc</name>
            <W>6</W>
            <H>3</H>
            <P>40</P>
        </product>
    </products>");

int w=7,h=3,p=40;


var totals = doc
    .Root
    .Elements("product")
    .Aggregate(
        Tuple.Create(0,0,0),
        (acc,el) => 
            Tuple.Create(
                acc.Item1 + (( (int)el.Element("W") ) < w ? 1 : 0),
                acc.Item2 + (( (int)el.Element("H") ) < h ? 1 : 0),
                acc.Item3 + (( (int)el.Element("P") ) < p ? 1 : 0)
            )
    );

Would give a tuple result with a value of: 将给出一个元组结果,其值为:

2, 0, 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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