【问题标题】:LINQ alternativeLINQ 替代方案
【发布时间】:2016-02-22 06:58:00
【问题描述】:

我有一本字典,我将把它转换成查询字符串。

var encryptionItems = new Dictionary<string,string>();
encryptionItems.Add("customerid", row.CustomerId.ToString());
encryptionItems.Add("firstname",model.FirstName); 
encryptionItems.Add("lastname",model.LastName);

var get = encryptionDal.EncryptDataWithSalt(encryptionItems, salt);
var linkUri = string.Empty;
foreach (var item in get)
{
    linkUri = string.Concat(linkUri, item.Key, "=", HttpUtility.UrlEncode(item.Value), "&");
}

我想以 LINQ 格式编写 foreach 循环来优化代码。 不知道该怎么做。谁能给我一些建议?

【问题讨论】:

  • LINQ 是否真的“优化代码”
  • 老实说,我会保持原样。 LINQ 实际上不会再有更高的性能,在某些情况下,我发现语法模糊了代码的意图,使其更难维护。
  • @MickyD - 不,LINQ 不会在性能方面“优化”代码。但它可能会在可读性方面“优化”代码。不过,这值得商榷。特别是如果开发人员自己(或团队成员)不习惯 LINQ。

标签: c# linq foreach


【解决方案1】:

您不需要显式循环。 String.Join() 就是为此而生的。

var encrypted = encryptionDal.EncryptDataWithSalt(encryptionItems, salt); // assuming it returns a Dictionary<string, string>
var queryString = String.Join("&",
    from kvp in encrypted
    select $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"
);

另一方面,您可能不希望使用 LINQ 的开销。如果要使用循环,请在要添加的字符串数量可能未知时使用StringBuilder

var encrypted = encryptionDal.EncryptDataWithSalt(encryptionItems, salt);
var sb = new StringBuilder();
foreach (var kvp in encrypted)
    sb.AppendFormat("&{0}={1}", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value));
var queryString = sb.ToString(1, sb.Length-1); // assuming non-empty

【讨论】:

    【解决方案2】:

    说实话,我会保持原样。 LINQ 实际上不会再有更高的性能,在某些情况下,我发现语法掩盖了代码的意图,使其更难维护。

    话虽如此,但我能提供的最短答案是:

      var encryptionItems = new Dictionary<string, string>
      {
        {"customerid", row.CustomerId.ToString()},
        {"firstname", model.FirstName},
        {"lastname", model.LastName}
      };
    
      var get = encryptionDal.EncryptDataWithSalt(encryptionItems, salt);
      var linkUri = get.Aggregate(string.Empty, (current, item) => string.Concat(current, item.Key, "=", HttpUtility.UrlEncode(item.Value), "&"));
    

    【讨论】:

      【解决方案3】:
      var linkUri = get.Aggregate(string.Empty,
                          (current, item) => string.Concat(current, item.Key, "=", HttpUtility.UrlEncode(item.Value), "&"));
      

      【讨论】:

        猜你喜欢
        • 2020-04-08
        • 2011-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-27
        • 2012-10-05
        相关资源
        最近更新 更多