我有一个字典“roomDict”,并希望从每个Room类中创建一个字符串属性“roomName”的列表。请帮忙!
这是我之前使用List:
List<string> roomNames = RoomManager.roomDict.Select(rm => rm.roomData.roomName).ToList();
但是现在我已经将列表声明为dict,我似乎无法找出相应的代码:
public static Dictionary<Guid, Room> roomDict = new Dictionary<Guid, Room>();
我需要一个字符串List来填充Unity中的下拉列表。提前谢谢!
里克多维
答案 0 :(得分:2)
List<string> roomNames = roomDict.Values.Select(rm => rm.roomData.roomName).ToList();
答案 1 :(得分:2)
根据我的理解,您有一个Dictionary<Guid,Room>
要转换为Dictionary<Guid,string>
,其中字符串是与Guid一起使用的房间的名称。 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。
答案 2 :(得分:1)
您可以使用Values
属性来获取房间:
var express = require('express');
var router = express.Router();
// Get Page model
var Page = require('../models/page');
/*
* GET /
*/
router.get('/', function (req, res) {
Page.findOne({slug: 'home'}, function (err, page) {
if (err)
console.log(err);
res.render('index', {
title: page.title,
content: page.content
});
});
});
/*
* GET a page
*/
router.get('/:slug', function (req, res) {
var slug = req.params.slug;
Page.findOne({slug: slug}, function (err, page) {
if (err)
console.log(err);
if (!page) {
res.redirect('/');
} else {
res.render('index', {
title: page.title,
content: page.content
});
}
});
});
// Exports
module.exports = router;
答案 3 :(得分:1)
您可以将对象直接放入组合框中。组合框调用.ToString来显示。只需覆盖Room Class中的.ToString,您就可以在选择中获得对象的所有属性。
public class Room
{
public int Width { get; set; }
public int Length { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
private void btnFillCombo_Click(object sender, EventArgs e)
{
foreach (KeyValuePair<int,Room> rm in dctRoom)
{
comboBox1.Items.Add(rm.Value);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Room rm = (Room)comboBox1.SelectedItem;
Debug.Print($"Name is {rm.Name}, Width is {rm.Width}, Length is {rm.Length}");
}
使用Debug.Print导入System.Diagnostics