![](/img/trans.png)
[英]Dictionary<string, int> to List<Dictionary<string, int>> in c#
[英]How to check if string s is inside of the List<string> in Dictionary<int, List<string>> in c#?
我有一个Dictionary<int, List<string>>
enrolledStudents
key
是一个整数,它是一个纸质代码。 该value
是字符串列表,其中字符串是学生姓名
我想知道的是如何检查string s
是否在enrolledStudents
此List中
例如
if(string s in List<string> of enrolledStudents){
return enrolledStudent.key;
}
要获取特定学生的所有书面代码,您可以执行以下操作:
List<int> paperCodesForStudent = enrolledStudents
.Where(item => item.Value.Contains("studentName"))
.Select(item => item.Key)
.ToList();
您可以将此方法用作方法,还可以为名称检查添加不区分大小写的比较:
private static List<int> GetPaperCodesForStudent(string studentName,
Dictionary<int, List<string>> enrolledStudents)
{
return enrolledStudents
.Where(item => item.Value.Any(name =>
name.Equals(studentName, StringComparison.OrdinalIgnoreCase)))
.Select(item => item.Key)
.ToList();
}
使用LINQ
return enrolledStudents.FirstOrDefault(kvp => kvp.Value.Contains(s)).Key;
请注意,此搜索是线性的。 如评论中所述,您可以一次重新创建另一个词典以优化搜索速度。
Dictionary<string, List<int>> pageMap = enrolledStudents
.SelectMany(kvp =>
kvp.Value.Select(value => new { Key = value, Value = kvp.Key }))
.GroupBy(a => a.Key)
.ToDictionary(a => a.Key, a => a.Select(x => x.Value).ToList());
现在,您可以使用pagemap这样从学生那里获取页面。
return pageMap[s];
Dictionary<int, List<string>> enrolledStudents = new Dictionary<int, List<string>>();
bool any = enrolledStudents.Any(x => x.Value.Contains("myString"));
或者如果您想要第一个钥匙
var key = enrolledStudents.FirstOrDefault(kvp => kvp.Value.Contains(s))?.Key ?? "";
请注意,如果FirstOrDefault()返回null,则使用单个问号。
不使用LINQ的解决方案
//第一个解决方案
Dictionary<int, List<string>> group = new Dictionary<int, List<string>>();
List<string> newList = new List<string> { "Orange", "Strawberry", "Banana"};
group.Add(1, newList); //Group of Fruits
newList = new List<string> { "Hulk", "Spiderman", "Batman" };
group.Add(2, newList); //Group of Super-Heroes
int GroupKey = 0;
foreach(var groupItem in group)
{
foreach(var stringValue in groupItem.Value)
{
if(stringValue == "Spiderman")
{
GroupKey = groupItem.Key;
break;
}
}
if(GroupKey > 0)
break
}
//我认为您应该在案例中使用的第二种解决方案(因为每个学生只有一个键(数字),也许只有在与学生群体一起工作时才使用字符串而不是List更好)您应该考虑第一种解决方案)
Dictionary<int, string> enrolledStudents = new Dictionary<int, string>();
enrolledStudents.Add(1, "Jamie Fox"); //Student 1
enrolledStudents.Add(2, "Arnold Spenser"); //Student 2
enrolledStudents.Add(3, "Jack & Jones"); //Student 3
int StudentNumber = 0;
foreach (var student in enrolledStudents)
{
if(student.Value == "Arnold Spenser")
{
StudentNumber = student.Key;
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.