给c#中字典中的集合赋值

本文关键字:集合 赋值 字典 | 更新日期: 2023-09-27 18:05:23

嗨,我需要从字典中给集合赋值。我的示例代码在

下面
public student
{
    public string Name { get; set;}
    public int Age { get; set;}
    public string Address { get; set;}
}

和我的字典集合是

Dictionary<string, Int16> StudentList= new Dictionary<string, Int16>();
StudentList.Add("Mahesh Chand", 35);
StudentList.Add("Mike Gold", 25);
StudentList.Add("Praveen Kumar", 29);
StudentList.Add("Raj Beniwal", 21);
StudentList.Add("Dinesh Beniwal", 84);

现在我的学生集合将只值名字列表,现在我需要使用linq为集合分配年龄,而不需要go for foreach,这在c#中可能吗?

给c#中字典中的集合赋值

你可以选择所有的KeyValuePair<string, int>,然后你可以初始化每个学生:

List<Student> students = AuthorList
    .Select(kv = > new Student{ Name  = kv.Key, Age = kv.Value })
    .ToList();

:

我想在学生集合中插入年龄取决于学生名称,为此目的,我使用名称-年龄字典集合作为查找,清楚了吗?

然后需要某种循环,注意LINQ中的Q代表查询。它不是更新集合的正确工具。

但是,您可以使用Enumerable.Join有效地将两个集合与LINQ连接起来,以准备foreach:

List<Student> allStudents = getYourStudents();
// link all known students in the name-age-dictionary with this collection:
var studentInfos = from s in allStudents
                   join sa in StudentList.Keys
                   on s.Name equals sa
                   select new { Student = s, Age = StudentList[sa] };
foreach (var s in studentInfos)
    s.Student.Age = s.Age;
var collection = dictionary.SelectMany(v => v.Value);