簡體   English   中英

使用 LINQ 從文件中選擇未知值

[英]Using LINQ to select unknown values from files

我有幾個文本文件,其中包含與機器代碼相關的信息。 下面是其中一個文件中的內容片段。

 <Parameter Name="Thickness" Idx="0" Val="0.8" Default="0.8" Min="0" Max="200" Show="True" Inherit="False" />

我正在嘗試使用 LINQ 來從該特定文本行中提取信息。 這是我到目前為止所擁有的。

 var thickness = from t in text
                 where t.Contains("Thickness") && t.Contains("Idx=0") && t.Contains("Val")
                 select t;

我需要從這行文本中獲取“Val”,在這種情況下應該是 0.8。 請有人啟發我如何做到這一點? 我做了一些研究,但我找不到明確的答案。

謝謝你。

這是我理解的一個示例,因為您嘗試使用 linq 而不是多種 EZ 方法,所以現在您可以添加任何 where 條件並調整選擇

void Main()
{
    string s= "<Parameter Name=\"Thickness\" Idx=\"0\" Val=\"0.8\" Default=\"0.8\" Min=\"0\" Max=\"200\" Show=\"True\" Inherit=\"False\" />";
    var doc = new XmlDocument();
    doc.LoadXml(s);
    
    var attr = doc.FirstChild
                    .Attributes
                    .Cast<XmlAttribute>()
                    .ToList()
                    .Select(s=> $"{s.Name} == {s.Value}");
    Console.Write(attr);

}

在此處輸入圖像描述

使用XDocument ,您可以將文件轉換為具有單個根,然后使用 LINQ to XML 進行查詢。

首先,將文件轉換為XDocument 注意:如果您的文件非常大,或者您不想將所有行讀入內存然后創建一個非常大的字符串,您可以使用IEnumerable<string>Stream轉換器和File.ReadLines()來減少開銷。

如果srcFile1包含文件中的行,則使用以下命令創建行的XElement集合:

var data1 = XDocument.Parse("<data>" + srcFile1.Join('\n') + "</data>").Root.Elements();

注意: Join是明顯的擴展方法。

現在您可以查詢這些行並提取Val屬性值:

var ans = data1.Where(d => d.AttrVal("Name") == "Thickness" && d.AttrVal("Idx") == "0" && d.HasAttr("Val"))
               .Select(d => d.AttrVal("Val"))
               .ToList();

我使用了一些簡單的擴展方法使其更短:

public static class XMLExt {
    public static string AttrVal(this XElement x, string name) => x.Attribute(name)?.Value;
    public static bool HasAttr(this XElement x, string name) => x.Attribute(name) != null;
}

謝謝大家的有用答案。 我已將他們帶入並感謝他們的幫助。

我決定使用子字符串。 請參閱下面我使用的方法。

var _thickness = (from row in lines
                 where row.Contains("Thickness") && row.Contains("Idx=\"0\"")
                 select row).First();

int thickStartIndex = _thickness.IndexOf("Val=");
thickStartIndex = thickStartIndex + 5;
int thickEndIndex = _thickness.IndexOf("Default");
string thickValue = _thickness.Substring(thickStartIndex, thickEndIndex - thickStartIndex - 2);

輸出 = 0.8

暫無
暫無

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

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