[英]Assign value to collection from dictionary in c#
嗨,我需要為字典中的集合賦值。 我的示例代碼如下
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為基於集合的鍵名分配年齡,而無需使用for foreach
,這在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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.