Domanda

Sono interessato: qual è l'analogo di C # di std::pair in C ++? Ho trovato System.Web.UI.Pair classe, ma preferirei qualcosa basato sul modello.

Grazie!

È stato utile?

Soluzione

Tuple sono disponibili da .NET4. 0 e supporto generici:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

Nelle versioni precedenti è possibile utilizzare System.Collections.Generic.KeyValuePair<K, V> o una soluzione come la seguente:

public class Pair<T, U> {
    public Pair() {
    }

    public Pair(T first, U second) {
        this.First = first;
        this.Second = second;
    }

    public T First { get; set; }
    public U Second { get; set; }
};

E usalo in questo modo:

Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);

Questo output:

test
2

O anche questa coppia incatenata:

Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;

Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);

Che genera:

test
12
true

Altri suggerimenti

System.Web.UI conteneva la classe Pair perché era ampiamente utilizzata in ASP.NET 1.1 come struttura ViewState interna.

Aggiornamento ago 2017: C # 7.0 / .NET Framework 4.7 fornisce una sintassi per dichiarare una Tupla con elementi nominati usando System.ValueTuple struct.

//explicit Item typing
(string Message, int SomeNumber) t = ("Hello", 4);
//or using implicit typing 
var t = (Message:"Hello", SomeNumber:4);

Console.WriteLine("{0} {1}", t.Message, t.SomeNumber);

vedi MSDN per altri esempi di sintassi.

Aggiornamento giugno 2012: Tuples fanno parte di .NET dalla versione 4.0.

Ecco un articolo precedente che descrive l'inclusione in.NET4.0 e supporto per generici:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

Purtroppo non ce n'è. Puoi utilizzare System.Collections.Generic.KeyValuePair<K, V> in molte situazioni.

In alternativa, puoi utilizzare tipi anonimi per gestire le tuple, almeno a livello locale:

var x = new { First = "x", Second = 42 };

L'ultima alternativa è creare una propria classe.

C # ha tuple dalla versione 4.0.

Alcune risposte sembrano sbagliate,

  1. non puoi usare il dizionario come memorizzerebbe le coppie (a, b) e (a, c). Il concetto di coppia non deve essere confuso con la ricerca associativa di chiavi e valori
  2. gran parte del codice sopra sembra sospetto

Ecco la mia classe di coppia

public class Pair<X, Y>
{
    private X _x;
    private Y _y;

    public Pair(X first, Y second)
    {
        _x = first;
        _y = second;
    }

    public X first { get { return _x; } }

    public Y second { get { return _y; } }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;
        if (obj == this)
            return true;
        Pair<X, Y> other = obj as Pair<X, Y>;
        if (other == null)
            return false;

        return
            (((first == null) && (other.first == null))
                || ((first != null) && first.Equals(other.first)))
              &&
            (((second == null) && (other.second == null))
                || ((second != null) && second.Equals(other.second)));
    }

    public override int GetHashCode()
    {
        int hashcode = 0;
        if (first != null)
            hashcode += first.GetHashCode();
        if (second != null)
            hashcode += second.GetHashCode();

        return hashcode;
    }
}

Ecco un codice di prova:

[TestClass]
public class PairTest
{
    [TestMethod]
    public void pairTest()
    {
        string s = "abc";
        Pair<int, string> foo = new Pair<int, string>(10, s);
        Pair<int, string> bar = new Pair<int, string>(10, s);
        Pair<int, string> qux = new Pair<int, string>(20, s);
        Pair<int, int> aaa = new Pair<int, int>(10, 20);

        Assert.IsTrue(10 == foo.first);
        Assert.AreEqual(s, foo.second);
        Assert.AreEqual(foo, bar);
        Assert.IsTrue(foo.GetHashCode() == bar.GetHashCode());
        Assert.IsFalse(foo.Equals(qux));
        Assert.IsFalse(foo.Equals(null));
        Assert.IsFalse(foo.Equals(aaa));

        Pair<string, string> s1 = new Pair<string, string>("a", "b");
        Pair<string, string> s2 = new Pair<string, string>(null, "b");
        Pair<string, string> s3 = new Pair<string, string>("a", null);
        Pair<string, string> s4 = new Pair<string, string>(null, null);
        Assert.IsFalse(s1.Equals(s2));
        Assert.IsFalse(s1.Equals(s3));
        Assert.IsFalse(s1.Equals(s4));
        Assert.IsFalse(s2.Equals(s1));
        Assert.IsFalse(s3.Equals(s1));
        Assert.IsFalse(s2.Equals(s3));
        Assert.IsFalse(s4.Equals(s1));
        Assert.IsFalse(s1.Equals(s4));
    }
}

Se si tratta di dizionari e simili, stai cercando System.Collections.Generic.KeyValuePair < TKey, TValue > ;.

A seconda di ciò che vuoi realizzare, potresti provare KeyValuePair .

Il fatto che non sia possibile modificare la chiave di una voce può ovviamente essere corretto semplicemente sostituendo l'intera voce con una nuova istanza di KeyValuePair.

Ho creato un'implementazione C # di Tuples, che risolve il problema genericamente tra due e cinque valori - ecco il post sul blog , che contiene un link alla fonte.

Stavo ponendo la stessa domanda subito dopo un rapido google ho scoperto che esiste una classe pair in .NET tranne che in System.Web.UI ^ ~ ^ ( http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx ) bontà sa perché lo hanno messo lì invece del framework delle collezioni

Da .NET 4.0 hai System.Tuple<T1, T2> classe:

// pair is implicitly typed local variable (method scope)
var pair = System.Tuple.Create("Current century", 21);

In genere estendo la classe Tuple nel mio wrapper generico come segue:

public class Statistic<T> : Tuple<string, T>
{
    public Statistic(string name, T value) : base(name, value) { }
    public string Name { get { return this.Item1; } }
    public T Value { get { return this.Item2; } }
}

e usalo in questo modo:

public class StatSummary{
      public Statistic<double> NetProfit { get; set; }
      public Statistic<int> NumberOfTrades { get; set; }

      public StatSummary(double totalNetProfit, int numberOfTrades)
      {
          this.TotalNetProfit = new Statistic<double>("Total Net Profit", totalNetProfit);
          this.NumberOfTrades = new Statistic<int>("Number of Trades", numberOfTrades);
      }
}

StatSummary summary = new StatSummary(750.50, 30);
Console.WriteLine("Name: " + summary.NetProfit.Name + "    Value: " + summary.NetProfit.Value);
Console.WriteLine("Name: " + summary.NumberOfTrades.Value + "    Value: " + summary.NumberOfTrades.Value);

Per far funzionare quanto sopra (avevo bisogno di una coppia come chiave di un dizionario). Ho dovuto aggiungere:

    public override Boolean Equals(Object o)
    {
        Pair<T, U> that = o as Pair<T, U>;
        if (that == null)
            return false;
        else
            return this.First.Equals(that.First) && this.Second.Equals(that.Second);
    }

e una volta che l'ho fatto ho anche aggiunto

    public override Int32 GetHashCode()
    {
        return First.GetHashCode() ^ Second.GetHashCode();
    }

per sopprimere un avviso del compilatore.

La libreria PowerCollections (precedentemente disponibile da Wintellect ma ora ospitata su Codeplex @ http://powercollections.codeplex.com ) ha una struttura di coppia generica.

Oltre alla classe personalizzata o alle tuple .Net 4.0, dal C # 7.0 esiste una nuova funzionalità chiamata ValueTuple, che è una struttura che può essere utilizzata in questo caso. Invece di scrivere:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

e accedi ai valori attraverso t.Item1 e t.Item2, puoi semplicemente farlo in questo modo:

(string message, int count) = ("Hello", 4);

o anche:

(var message, var count) = ("Hello", 4);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top