更"LINQ"的是一种搜索字符串文字的方法,或者,更具可读性的是什么? [英] A more "LINQ" way to search a String Literal, or, what is more readable?

查看:56
本文介绍了更"LINQ"的是一种搜索字符串文字的方法,或者,更具可读性的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我为苏打汽水公司"工作,不是真的,而是为了保护专有信息,所以我假装我这样做.我有一个ASPX页面,该页面传递了诸如
这样的查询字符串
http://www.sodaforu.com/page.aspx?brand=coke

好的,所以我想在代码中放置一个"if",以便如果我不传入我们的汽水品牌之一,那么我就不会做任何事情,因此,您不能在其中放入恶意代码查询字符串.

所以我想说,如果传递的品牌是空白或不是一组预定义的特定值之一,那么等等等等"

在我之前来的那个人是这样写的,这是合法的,但是他在字符串文字中使用了大约100个不同的空格分隔的名称,这使它偏离了VS窗口的边缘.

Okay, so I work for a "soda pop company," not really but to protect proprietary info, let''s pretend I do. And I have an ASPX page that is passed a querystring like

http://www.sodaforu.com/page.aspx?brand=coke

OK, so I want to place an "if" in the code so that if I don''t pass one of our soda brands in, I won''t do anything for instance, so you can''t put malicious code in the query string.

So I want to say, "if the brand passed is either blank or not one of a certain set of predefined specific values, then blah blah blah"

The guy who came before me wrote it this way, which is legal but he had about 100 different space-separated names in the string literal which makes it run off the edge of the VS window.

if (string.IsNullOrWhiteSpace(qsBrand) || !"coke pepsi sprite fanta barqs welchs 7-up A&W shasta dads pepsi drpepper".Contains(qsBrand))
{
    // whatever...
}



是否有任何更易读"的方式对此进行编码?也许使用LINQ/延迟执行?

Brian



Is there any "more readable" way to code this? Maybe using LINQ/Deferred Execution?

Brian

推荐答案

虽然不是最有效,但长字符串方法效果很好.我会声明一组不变的字符串,例如:
Though not most efficient, long string method works perfectly well. I''d declare a constant set of strings, like this:
private static readonly HashSet<string> LegalNames = new HashSet<string>(new[] {
    "coke"
,   "pepsi", ...
});</string></string>

,然后使用它来检查传入的查询,如下所示:

and then use it to check the incoming queries, like this:

if (string.IsNullOrWhiteSpace(qsBrand) || !LegalNames.Contains(qsBrand)) {...}

鉴于列表中的商品数量相对较少,我们谈论的是个人喜好问题:微不足道的效率提升不值得进行额外的打字.

Given a relatively small number of items on the list, we''re talking a matter of personal preference: the tiny efficiency gain is not worth the additional typing.


这篇关于更"LINQ"的是一种搜索字符串文字的方法,或者,更具可读性的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆