据我了解,您有一个 Dictionary<Guid,Room>,您想将其转换为 Dictionary<Guid,string>,其中的字符串是与 Guid 一起使用的房间的名称。向导当然应该保持不变。
这可以通过ToDictionary() 轻松完成,方法是更改值委托,使其返回Name 属性而不是Room 本身。包含四个元素的简单示例:
using System;
using System.Linq;
using System.Collections.Generic;
public class Room
{
public string Name { get; set; }
}
public class Program
{
public static void Main()
{
//Setup sample data
var roomDictionary = new Dictionary<Guid,Room>
{
{ Guid.NewGuid(), new Room { Name = "Room A" } },
{ Guid.NewGuid(), new Room { Name = "Room B" } },
{ Guid.NewGuid(), new Room { Name = "Room C" } },
{ Guid.NewGuid(), new Room { Name = "Room D" } }
};
//This is the magic line
var results = roomDictionary.ToDictionary
(
pair => pair.Key, //Keep existing key
pair => pair.Value.Name //Substitute Name property instead of the Room itself
);
//Output results
foreach (var pair in results)
{
Console.WriteLine("{0}={1}", pair.Key, pair.Value);
}
}
}
输出:
5cc94e3d-f9d3-448e-ad21-12feee335c2b=Room A
83bc6fca-38b0-4e6c-be3a-2e7be1e11932=Room B
ec9d15dd-0f8b-43b8-9db3-62630cf5821f=Room C
ef08e20c-65e0-43f2-953d-f285380b0a78=Room D
如果您想尝试一下,这里是link to a Fiddle。