没有KEY约束的字典或KeyValuePair

问题描述

| 我需要返回两个值的列表。 我尝试了Dictionary,但第一个参数是键,在我的情况下,它将重复。 我的列表需要返回如下内容: 经理-John Zambers 开发人员-Paul Myers 开发人员-John Zambers 测试员-玛丽·玛丽 等...-等... 我不想创建自己的类来表示此列表。 Dot.Net有一个内置的Type代表它吗?像List()这样的东西吗? 提前致谢。     

解决方法

您可以使用
System.Tuple<T1,T2>
类,例如:
List<Tuple<String,String>> people = new List<Tuple<String,String>>();
people.Add(Tuple.Create(\"Manager\",\"John Zambers\"));
// etc.
但是,创建自己的课程怎么了?它们几乎可以自我记录,尤其是在像这样的简单情况下(例如,很明显,
Name
字段中将是什么)。例如:
public class Person
{
   public string Role { get; set; }
   public string Name { get; set; }
}
旁注:我不知道您的应用程序域或您可能拥有的所有角色/标题,但是如果您基于此值进行任何处理,则似乎是改用
enum
的好地方。例如。,
public enum Roles
{
    Manager,Developer,Tester
}
    ,那这个呢?
Dictionary<string,List<string>> role_names = new Dictionary<string,List<string>>();
List<string> lst;

role_names.Add(\"Manager\",lst = new List<string>());
lst.Add(\"John Zambers\");

role_names.Add(\"Developer\",lst = new List<string>());
lst.Add(\"Paul Myers\");
lst.Add(\"John Zambers\");

role_names.Add(\"Tester\",lst = new List<string>());
lst.Add(\"Mary Marie\");
    ,尝试这个:
List<KeyValuePair<string,string>> list = new List<KeyValuePair<string,string>>();
list.Add(new KeyValuePair<string,string>(\"Manager\",\"John\"));
list.Add(new KeyValuePair<string,\"John\"));
Console.WriteLine(list[0].Key);
您也可以使用
System.Web.UI.Pair
之类的东西(虽然不是通用的,但有时很方便)。 但是,只有在第一件事是职位而第二件事是名字的确无关紧要的情况下,才应使用它。如果要将其视为另一对东西-使用KeyValuePair或Pair。但是,如果它是位置和名称对的列表,则为它创建一个特殊类型可能是个好主意。     ,.NET确实有此类的类,但是您不能直接使用它。它是
Lookup
,并由LINQ中的
ToLookup
方法返回。 如果您想出一种方法来在任何数据来源上使用ѭ10,它将使您的生活变得更加轻松。 如果需要,您始终可以使用我从Edulinq获得的
Lookup
实现。基本上,这两种实现都是从程序集本身外部不可变的,但是如果需要,可以将我的实现更改为可变的:)     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...