【问题标题】:an alternative to Enumerable.First (System.Linq) C#Enumerable.First (System.Linq) C# 的替代方案
【发布时间】:2016-12-20 06:12:29
【问题描述】:

我在 .net 3.5 中运行了这段代码

public const string SvgNamespace = "http://www.w3.org/2000/svg";
public const string XLinkPrefix = "xlink";
public const string XLinkNamespace = "http://www.w3.org/1999/xlink";
public const string XmlNamespace = "http://www.w3.org/XML/1998/namespace";

public static readonly List<KeyValuePair<string, string>> Namespaces = new List<KeyValuePair<string, string>>()
{
    new KeyValuePair<string, string>("", SvgNamespace),
    new KeyValuePair<string, string>(XLinkPrefix, XLinkNamespace),
    new KeyValuePair<string, string>("xml", XmlNamespace)
};

private bool _inAttrDictionary;
private string _name;
private string _namespace;

public string NamespaceAndName
        {
            get
            {
                if (_namespace == SvgNamespace)
                    return _name;
                return Namespaces.First(x => x.Value == _namespace).Key + ":" + _name;
            }
        }

我目前正在将其转换为 .net 2.0(删除 System.Linq)。如何维护在我的代码中找到 here 的 Enumerable.First Method (IEnumerable, Func) 的功能?

完整来源file

【问题讨论】:

  • 什么是命名空间?这里没有同名的变量
  • @Steve,有一个public static readonly List&lt;KeyValuePair&lt;string, string&gt;&gt; Namespaces
  • @Rahul 我现在看到了,但我的借口是,如果您查看发布的链接中的源代码,事情会变得非常混乱。
  • @Steve,哈哈,你真的浏览过那个源代码链接吗:)

标签: c# .net-3.5 .net-2.0


【解决方案1】:

您可能可以使用foreach 循环

foreach(var item in Namespaces)
{
  if(item.Value == _namespace)
    return item.Key + ":" + _name;
}

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

您可以按如下方式创建 GetFirst 方法:

    public string NamespaceAndName
    {
        get
        {
            if (_namespace == SvgNamespace)
                return _name;

            return GetFirst(Namespaces, _namespace).Key + ":" + _name;
        }
    }
    private KeyValuePair<string, string> GetFirst(List<KeyValuePair<string,string>> namespaces,string yourNamespaceToMatch)
    {
        for (int i = 0; i < namespaces.Count; i++)
        {
            if (namespaces[i].Value == yourNamespaceToMatch)
                return namespaces[i];
        }
        throw new InvalidOperationException("Sequence contains no matching element");
    }

【讨论】:

    【解决方案3】:

    它并不是Enumerable.First 的真正替代品,但由于您实际上有一个List&lt;T&gt; 变量,您可以考虑Find 方法。签名与Enumerable.First 兼容,但请注意,该行为与Enumerable.FirstOrDefault 兼容,即如果元素不存在,您将获得NRE 而不是“序列不包含匹配元素”。

    return Namespaces.Find(x => x.Value == _namespace).Key + ":" + _name;
    

    【讨论】:

    • 我也喜欢你的回答。
    猜你喜欢
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2011-08-24
    • 2011-11-10
    • 2011-06-12
    相关资源
    最近更新 更多