简体   繁体   English

将字符串对添加到列表中的更好方法是什么 <T> ?

[英]What is the better way to add pairs of strings into List<T>?

I need to create List whete T is pair of strings. 我需要创建List whete T是一对字符串。

I tryed to do that in most obvious way: 我试图以最明显的方式做到这一点:

public struct rule {
    public string left, right;
}

class Program {
    static void Main(string[] args) {
        List<rule> rules = new List<rule>();
        rules.Add(new rule("asd","asd"));
    }
}

I get that here needed constructor. 我得到这里需要的构造函数。 And now i think - creating class just to put some strings into list sounds wrong. 现在我想-创建类只是将一些字符串放入列表听起来是错误的。

Maybe here is any more simple way to do that? 也许这是更简单的方法吗?

Apart from using a separate class (you're doing it wrong anyway), you can use a Tuple<> . 除了使用单独的类(无论如何还是做错了)之外,您还可以使用Tuple<> While using KeyValuePair is also an option here, logically it will not be correct as it represents a key with a corresponding value, which is not you want as I understand. 虽然在这里也可以使用KeyValuePair逻辑上讲它并不正确,因为它代表具有相应值的键,据我所知,这不是您想要的。

List<Tuple<string, string>> rules = new List<Tuple<string, string>>();
rules.Add(Tuple.Create("aaa", "bbb"));

To repair you class approach you can do the following: 要修复您的课堂方法,您可以执行以下操作:

public struct rule {
    public string left, right;

    public rule(string left, string right) 
    {
        this.left = left;
        this.right = right;
    }
}

Or use auto-properties: 或使用自动属性:

public class rule
{
    public string left {get;set;}
    publci string right {get;set;}
}

And then in your main method: 然后在您的主要方法中:

rules.Add(new rule {right ="asd", left = "asd"});

我没有发现像上面那样添加类有什么问题,但是您可以使用KeyValuePair

Why not use KeyValuePair ? 为什么不使用KeyValuePair

class Program {
    static void Main(string[] args) {
        List<KeyValuePair<string, string>> rules = new List<KeyValuePair<string, string>>();
        rules.Add(new KeyValuePair<string, string>("asd","asd"));
    }
}

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

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