如何将泛型列表作为值添加到字典中<;字符串,列表<;餐厅>>;在c#.net中
本文关键字:lt gt 列表 net 字符串 餐厅 字典 泛型 添加 | 更新日期: 2023-09-27 18:01:15
public static void InitialiseRestaurantList(Dictionary<string, List<Restaurant>> allRestaurants)
{
var restaurants = new List<Restaurant>();
using (var sr = new StreamReader(@".'Restaurants.csv"))
{
while (sr.Peek() != -1)
{
var line = sr.ReadLine();
var fields = line.Split(',');
var obj = new Restaurant(fields[0], fields[1], fields[2], fields[3], fields[4]);
restaurants.Add(obj);
}
sr.Close();
}
List<Restaurant> PuneList = new List<Restaurant>();
foreach (Restaurant r in restaurants)
{
if (r.City.CompareTo("Pune")==0)
{
PuneList.Add(r);
}
}
Dictionary<string, List<Restaurant>> newDict = new Dictionary<string, List<Restaurant>();
**// How to add the PuneList as a value to this newDict...?**
}
Restaurant.csv
包含以下数据:
1,Mc Donald's,Pune,Kothrud,Near Karve Statue-29
2,Dominoes,Pune,Baner,Sappehire Chamber Pune-45
3,Faaso's,Pune,Kothrud,Karishma Society Karve Road Pune-29
4,Pizza Hut,Nagpur,Dharampeth,Laxmibhawan Square Nagpur-10
5,KFC,Nagpur,Ram Nagar,Near Nagpur University Nagpur-10
6,MainLand China,Nagpur,Azim Nagar,Near Guru Nanak College of Pharmacy Nagpur-10
7,Barbeque Nation,Goa,Margao,Near Majorda Beach Goa-01
8,Sigree,Goa,Mapusa,Near Vagator Beach Goa-07
9,Marakesh,Hyderabad,CBI Colony,Jubilee Hills Hyderabad-33
10,Yana's,Hyderabad,Secundarabad,Near Mallanna Temple Hyderabad-03
我已经将csv文件中的值放入一个通用的餐厅列表类型中,其中有5个字段放入一个列表中,现在我想将列表中的一个城市作为关键字,将列表的其余字段作为值,并将其作为参数传递给Dictionary。有人能帮我这样做吗?我可以按地区城市列出单独的餐厅名单。如何将泛型列表作为值传递给字典。
当您声明字典时,可以使用初始值设定项语法将项添加到字典中:
var newDict = new Dictionary<string, List<Restaurant>() {{"Pune", PuneList }};
然而,我相信最后10行左右的代码可以通过一些LINQ:来简化
var newDict = restaurants.Where(r => r.City.CompareTo("Pune") == 0)
.GroupBy(r => r.City)
.ToDictionary(r => r.Key, r => r.ToList());
编辑
一旦你将所有餐厅加载到列表中,你就可以将它们投影到一个由城市名称键入的Dictionary
中,然后你可以使用字典根据关键字(城市(进行搜索并迭代餐厅(我简化了你的Restaurant
(:
var restaurants = new List<Restaurant>
{
new Restaurant("Pune", "Mc Donald's", "Pune Address #1"),
new Restaurant("Pune", "Dominoes", "Pune Address #2"),
new Restaurant("Nagpur", "Pizza Hut", "Nagpur Address #1")
};
var newDict = restaurants.GroupBy(r => r.City)
.ToDictionary(r => r.Key, r => r.ToList());
foreach (var restaurant in newDict["Pune"])
{
Debug.WriteLine("City {0}, Address {1}, Brand {2}", restaurant.City,
restaurant.Address, restaurant.Brand);
}
输出:
City Pune, Address Pune Address #1, Brand Mc Donald's
City Pune, Address Pune Address #2, Brand Dominoes
只需使用"add"将其添加到字典中。
newDict.Add("Pune", PuneList);
然后您可以通过以下方式访问:
var puneList = newDict["Pune"];
如果你想检查字典是否包含密钥用法:
bool hasPune = newDict.ContainsKey("Pune");
点击此处阅读有关通用词典的更多信息。