简体   繁体   English

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

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

I have this piece of code running in .net 3.5 我在.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;
            }
        }

and I am currently converting it to .net 2.0 (removing System.Linq). 我目前正在将其转换为.net 2.0(删除System.Linq)。 How can I maintain the functionality of Enumerable.First Method (IEnumerable, Func) found here within my code? 如何在代码中找到此处Enumerable.First方法(IEnumerable,Func)的功能

Full source file 完整的源文件

You can probably use a foreach loop like 您可能可以使用如下的foreach循环

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

You can create GetFirst method as follows: 您可以如下创建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");
    }

It's not really an alternative to Enumerable.First , but since you have actually a List<T> variable, you can consider Find method. 它实际上不是Enumerable.First的替代方法,但是由于实际上有一个List<T>变量,因此可以考虑使用Find方法。 The signature is compatible with the Enumerable.First , but note that the behavior is compatible with Enumerable.FirstOrDefault , ie in case the element doesn't exist, you'll get NRE instead of the "Sequence contains no matching element". 签名与Enumerable.First兼容,但请注意,行为与Enumerable.FirstOrDefault兼容,即,如果元素不存在,则将获得NRE而不是“序列不包含匹配元素”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM