2016-08-13 4 views
2

Iは、コードのこの部分は、.NET 3.5Enumerable.First(System.Linqの)に代わるC#

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; 
      } 
     } 

で実行されていると私は現在、(System.Linqのを取り除く)2.0を.NETに変換してい有します。 Enumerable.Firstメソッド(IEnumerable、Func)の機能を維持する方法hereはコード内にありますか?

完全なソースfile

+0

_Namespaces_とは何ですか?この名前の変数はありません – Steve

+0

@Steve、1つの 'public static readonly List > Namespaces' – Rahul

+0

@Rahul私はそれを今見ていますが、私の言い訳では、ソースコードを見ると投稿されたリンクでは、物事は本当に混乱します。 – Steve

答えて

1

あなたは、おそらく次のようにあなたがのGetFirstメソッドを作成することができます

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

助けてくれてありがとう! – Robokitty

1

ようforeachループを使用することができます。

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"); 
    } 
1

それは本当にEnumerable.Firstに代わるものではありませんが、実際にはList<T>という変数があるので、Findのmeth od。署名はEnumerable.Firstと互換性がありますが、動作はEnumerable.FirstOrDefaultと互換性があります。つまり、要素が存在しない場合は、「シーケンスに一致する要素がありません」ではなくNREを取得します。

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

私はあなたの答えも好きです。 – Robokitty

関連する問題