Enumerable.First (System.Linq) C# 的替代方法

an alternative to Enumerable.First (System.Linq) C#

我在 .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)。如何维护 Enumerable.First Method (IEnumerable,‖Func) found here in my code 的功能?

完整来源file

您可以使用 foreach 循环,例如

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

您可以按如下方式创建 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");
    }

它并不是 Enumerable.First 的真正替代方法,但由于您实际上有一个 List<T> 变量,您可以考虑 Find 方法。签名与 Enumerable.First 兼容,但请注意行为与 Enumerable.FirstOrDefault 兼容,即如果元素不存在,您将获得 NRE 而不是 "Sequence contains no matching element"。

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