簡體   English   中英

C#總結一個列表中的多個項目

[英]C# sum up multiple items in a list

我想我只需要一點幫助,因為我在這里繞圈子有一個小問題。

這是來自以特殊 xml 格式存儲文件的部署服務器的報告。

該文件如下所示:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<feed xml:base="XXXXX:9801/MDTMonitorData/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
<title type="text">Computers</title>
<id>XXXXXXX:9801/MDTMonitorData/Computers/</id>
<updated>2020-02-26T06:49:07Z</updated>
<link rel="self" title="Computers" href="Computers" />
  <entry>
  <id>http://XXXXXXX:9801/MDTMonitorData/Computers(72)</id>
  <title type="text"></title>
  <updated>2020-02-26T07:24:45Z</updated>
  <author>
    <name />
  </author>
  <link rel="edit" title="Computer" href="Computers(72)" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ComputerIdentities" type="application/atom+xml;type=feed" title="ComputerIdentities" href="Computers(72)/ComputerIdentities" />
  <category term="MDT_MonitorModel.Computer" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
  <content type="application/xml">
    <m:properties>
      <d:Name>NB-DE-00011</d:Name>
      <d:PercentComplete m:type="Edm.Int16">100</d:PercentComplete>
      <d:Settings m:null="true" />
      <d:Warnings m:type="Edm.Int32">0</d:Warnings>
      <d:Errors m:type="Edm.Int32">0</d:Errors>
      <d:DeploymentStatus m:type="Edm.Int32">3</d:DeploymentStatus>
      <d:StartTime m:type="Edm.DateTime">2020-02-25T07:33:15.797</d:StartTime>
      <d:EndTime m:type="Edm.DateTime">2020-02-25T08:02:26.653</d:EndTime>
      <d:ID m:type="Edm.Int32">72</d:ID>
      <d:UniqueID m:type="Edm.Guid">509c118c-3489-42c0-91ed-bf5695872a28</d:UniqueID>
      <d:CurrentStep m:type="Edm.Int32">91</d:CurrentStep>
      <d:TotalSteps m:type="Edm.Int32">91</d:TotalSteps>
      <d:StepName></d:StepName>
      <d:LastTime m:type="Edm.DateTime">2020-02-25T08:02:26.653</d:LastTime>
      <d:DartIP m:null="true" />
      <d:DartPort m:null="true" />
      <d:DartTicket m:null="true" />
      <d:VMHost m:null="true" />
      <d:VMName m:null="true" />
    </m:properties>
  </content>
</entry>
<entry>
  <id>http://XXXXXXX:9801/MDTMonitorData/Computers(71)</id>
  <title type="text"></title>
  <updated>2020-02-26T07:24:45Z</updated>
  <author>
    <name />
  </author>
  <link rel="edit" title="Computer" href="Computers(71)" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ComputerIdentities" type="application/atom+xml;type=feed" title="ComputerIdentities" href="Computers(71)/ComputerIdentities" />
  <category term="MDT_MonitorModel.Computer" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
  <content type="application/xml">
    <m:properties>
      <d:Name>NB-DE-00210</d:Name>
      <d:PercentComplete m:type="Edm.Int16">100</d:PercentComplete>
      <d:Settings m:null="true" />
      <d:Warnings m:type="Edm.Int32">0</d:Warnings>
      <d:Errors m:type="Edm.Int32">0</d:Errors>
      <d:DeploymentStatus m:type="Edm.Int32">3</d:DeploymentStatus>
      <d:StartTime m:type="Edm.DateTime">2020-02-24T09:01:43.483</d:StartTime>
      <d:EndTime m:type="Edm.DateTime">2020-02-24T09:30:54.38</d:EndTime>
      <d:ID m:type="Edm.Int32">71</d:ID>
      <d:UniqueID m:type="Edm.Guid">0b3cff76-b983-4ac4-bc13-cd36c25318db</d:UniqueID>
      <d:CurrentStep m:type="Edm.Int32">91</d:CurrentStep>
      <d:TotalSteps m:type="Edm.Int32">91</d:TotalSteps>
      <d:StepName></d:StepName>
      <d:LastTime m:type="Edm.DateTime">2020-02-24T09:30:54.63</d:LastTime>
      <d:DartIP m:null="true" />
      <d:DartPort m:null="true" />
      <d:DartTicket m:null="true" />
      <d:VMHost m:null="true" />
      <d:VMName m:null="true" />
    </m:properties>
  </content>
</entry>

不幸的是,我還沒有找到一種合理的方法來將每個條目中的所有屬性放入一個列表中。

到目前為止,我創建了一個具有屬性的類,現在我想把這個糟糕的東西放在一個列表中。

計划:讓我們假設該列表被稱為:mdtobject

MDTObject[0]:
Attr: Name | Value: NB-DE..
Attr:PercentComplete | Value 100

所以一個..

在 C# 中

var total = mdtobject.Sum(x => x.[INSERT PROPERTY OF List ITEM TO SUMMED HERE])

使用 xml linq 並將結果放入字典中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XNamespace mNs = doc.Root.GetNamespaceOfPrefix("m");
            XNamespace dNs = doc.Root.GetNamespaceOfPrefix("d");

            Dictionary<string, string> dict = doc.Descendants(mNs + "properties").Elements()
                .GroupBy(x => x.Name.LocalName, y => (string)y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }
}

對於多個條目,請使用以下內容:

            Dictionary<string, Dictionary<string, string>> dict2 = doc.Descendants(ns + "entry")
                .GroupBy(x => (string)x.Element(ns + "id"), y => y)
                .ToDictionary(x => x.Key, y => y.Descendants(mNs + "properties").FirstOrDefault().Elements()
                  .GroupBy(a => a.Name.LocalName, b => (string)b)
                  .ToDictionary(a => a.Key, b => b.FirstOrDefault()));

這是簡單的 XML 操作。 你可以試試這個代碼。

public static List<Dictionary<string, object>> ParseXml(XDocument xd)
    {
        var namespaceM = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
        var namespaceD = "http://schemas.microsoft.com/ado/2007/08/dataservices";
        var ret = new List<Dictionary<string, object>>();
        var entryElements = xd.Descendants(XName.Get("entry", "http://www.w3.org/2005/Atom"));
        foreach (var entryElement in entryElements)
        {
            var propertiesElement = entryElement.Descendants(XName.Get("properties", namespaceM)).FirstOrDefault();
            if (propertiesElement != null)
            {
                var dict = new Dictionary<string, object>();
                var propertyElements = propertiesElement.Descendants();
                foreach (var propertyElement in propertyElements)
                {
                    var name = propertyElement.Name.LocalName;
                    var value = propertyElement.Value;
                    var typeAttr = propertyElement.Attribute(XName.Get("type", namespaceM));
                    var nullAttr = propertyElement.Attribute(XName.Get("null", namespaceM));
                    if (nullAttr != null && nullAttr.Value == "true")
                    {
                        dict.Add(name, null);
                    }
                    else if (typeAttr != null)
                    {
                        switch (typeAttr.Value)
                        {
                            case "Edm.Int16":
                                dict.Add(name, Convert.ToInt16(value));
                                break;
                            case "Edm.Int32":
                                dict.Add(name, Convert.ToInt32(value));
                                break;
                            case "Edm.DateTime":
                                dict.Add(name, Convert.ToDateTime(value));
                                break;
                            case "Edm.Guid":
                                dict.Add(name, Guid.Parse(value));
                                break;
                        }
                    }
                    else
                    {
                        dict.Add(name, value);
                    }
                }
                ret.Add(dict);
            }

        }
        return ret;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM