如何在 C# 中使用 lambda 表达式检测元素是否存在?

发布于 2024-12-08 07:10:46 字数 331 浏览 0 评论 0原文

我一直在使用 try/catch 语句来判断元素在解析时是否存在。显然这不是最好的方法。我一直在使用 LINQ(lambda 表达式)进行大部分解析,但我只是不知道如何检测元素是否存在。

我发现一些解决方案的一个大问题是,它们需要比使用 try/catch 块多 3-4 倍的代码,这有点违背了目的。

我假设代码看起来像这样:

if(document.Element("myElement").Exists())
{
   var myValue = document.Element("myElement").Value;
}

我确实找到了这个

I've been using a try/catch statement to run through whether or not an element exists when I parse through it. Obviously this isn't the best way of doing it. I've been using LINQ (lambda expressions) for the majority of my parsing, but I just don't know how to detect if an element is there or not.

One big problem with some solutions I found is that they take 3-4 times more code than using the try/catch block, which kind of defeats the purpose.

I would assume the code would look something like this:

if(document.Element("myElement").Exists())
{
   var myValue = document.Element("myElement").Value;
}

I did find this link, but the looping is unecessary in my case as I can guarantee that it will only show up once if it exists. Plus the fact of having to create a dummy element which seems unecessary as well. Doesn't seem like it's the best way (or a good way) of checking. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浪推晚风 2024-12-15 07:10:46
XElement e = document.Element("myElement");
if (e != null)
{
    var myValue = e.Value; 
}

http://msdn.microsoft.com/en -us/library/system.xml.linq.xcontainer.element.aspx

“获取具有指定 XName 的第一个(按文档顺序)子元素。”

“如果不存在具有指定名称的元素,则不返回任何内容。”

XElement e = document.Element("myElement");
if (e != null)
{
    var myValue = e.Value; 
}

http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx

"Gets the first (in document order) child element with the specified XName."

"Returns Nothing if there is no element with the specified name."

夜灵血窟げ 2024-12-15 07:10:46

Any() 是 Linq 命令。

Assert.IsFalse( new [] { 1, 2, 3, 4 }.Any( i => i == 5 ));

Any() is the Linq command.

Assert.IsFalse( new [] { 1, 2, 3, 4 }.Any( i => i == 5 ));
青朷 2024-12-15 07:10:46

顺便说一句,上面关于“try / catch”的评论可能是正确的,但并非在几乎所有情况下都是正确的。这取决于您如何构建解决方案。在您的发布版本中,尽可能多地关闭那些即使从远处看也像“调试”的标志。在构建过程中,运行时被告知记住堆栈跟踪和内容的次数越少,“try / catch”的速度就越快。

顺便说一句,#2:著名的架构模式“告诉,不要问!” (TDA) 和“开闭原则”(OCP) 禁止使用诸如“if (!(fp = fopen(...))”之类的臭名昭著的代码。它们不仅鼓励你使用“try / catch”但强迫你这样做,因为OCP不仅要求在你自己的代码中遵守,而且在调用外国东西(即像stdio这样的库)时也要求遵守

。因为你不被允许扩大现有代码的含义。坚持简单的“fopen”示例,当结果为零时,您要做什么?为什么“fopen”失败?您可以检查是否有足够的空白空间,或者文件是否存在。如果文件名有效的话,系统是可写的。但是,您的目标仍然无法实现:想象一下无头应用程序,那么现在没有理由这样做吗?进一步摸索这些东西,因为“fopen”失败了。如果“fopen”失败了,那么它就失败了

。如果您的代码可能会因结果集通常可能包含或不包含元素而“失败”,请将逻辑放入类中。也许您必须在不同的类 (TDA) 之间分发数据、属性、问题和方法。也许您必须根据 SLA 重新调整您的代码。

不过,就您而言,请确保该元素存在。如果你做不到,那不是你的错。在代码深处(一个包装器,其中前编码员的所有错误都得到美化),将所需的数据转换为另一个实体,这样就不需要“如果”了。

Btw, the comment above about "try / catch" can be true, but isn't in almost all cases. It depends on how you build your solution. In your Release build, turn off as much flags as possible that smell like "Debug" even from a distance. The less the runtime has been told to memorize stack traces and stuff during building, the faster "try / catch" becomes.

Btw, #2: The famous architectural patterns "Tell, don't ask!" (TDA) and the "Open Close Principle" (OCP) forbid the usage of such infamous code like "if (!(fp = fopen(...))". They don't just encourage you to use "try / catch" but force you to do so. Because the OCP not only demands to obey within your own code but also when calling foreign stuff (i.e. libraries like stdio).

Why OCP, not TDA in the last sentence? Because you're not allowed to widen the meaning of existing code. Sticking to the simple "fopen" example, what are you going to do when the result is Zero? Why exactly did "fopen" fail? You could check wether there's enough empty space left, or if the file system is writeable. Of if the file name is valid. Or whatnot. Still, your goal cannot be achieved: open the file. Imagine a headless application, so no intervention of the user is possible. Now what? There is exactly no reason to further fumble with the stuff, because "fopen" failed. You'll need a fallback strategy. Dot. If "fopen" has failed, it has failed.

Rule of thumb: Think of your code as always succeeding (KIS). If your code willingly may 'fail' in terms of that a result set regularly may contain elements or not, put the logic into the class. Perhaps you have to distribute data, properties, and questions, and methods across different classes (TDA). Perhaps you have to readjust your code according to SLA.

In your case, though, make sure the element is existing. If you cannot, it's not your fault. Deep down in your code (a wrapper where all the mistakes of former coders get beautified), transform the data needed into another entity such that further up there is no need to "if".

笑梦风尘 2024-12-15 07:10:46

Any() 是检查元素是否存在的最简单方法。

如果您必须确保元素是唯一的,则必须执行类似 .Count() == 1 的操作。或者,您可以实现自己的扩展方法,但这只是 .Count == 1 的包装。

Any() is the simplest way to check if an element exists.

If you have to make sure that the element is unique, you'll have to do something like .Count() == 1. Alternatively you could implement your own extension method, but this would be only a wrapper around .Count == 1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文