I have a dictionary that uses a combination of string.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<People> listName = new List<People>(){
new People(){firstname = "David", middlename = "Broom", lastname = "Lightning", value = 1},
new People(){firstname = "Dave", middlename = "Cak", lastname = "Londo", value = 2},
new People(){firstname = "Chris", middlename = "Vanglein", lastname = "Walls", value = 3},
new People(){firstname = "Rudy", middlename = "Affair", lastname = "Master", value = 4}};
Dictionary<(string, string, string), List<People>> data = listName
.Where(x => x.value != 0)
.GroupBy(x => (x.firstname, x.middlename, x.lastname))
.ToDictionary(x => x.Key, x => x.ToList());
}
public class People {
public string firstname {get; set;}
public string middlename {get; set;}
public string lastname {get; set;}
public int value {get; set;}
}
}
https://dotnetfiddle.net/dGTHv7
how to get a value when I just have 2 key firstname and lastname.
I want to get all that match firstname and lastname and ignore middlename.
There is no point of having a dictionary where the key is a combination of these 3 information if you need to retrieve data with only 2 information.
What about parsing the list directly?
var matchingPeople = listName.Where(p => p.firstname == "myfirstname" && p.lastname == "mylastname");
EDITED: Then you need to do that:
var listName = new List<People>
{
new People { firstname = "David", middlename = "Broom", lastname = "Lightning", value = 1 },
new People { firstname = "Dave", middlename = "Cak", lastname = "Londo", value = 2 },
new People { firstname = "Chris", middlename = "Vanglein", lastname = "Walls", value = 3 },
new People { firstname = "Rudy", middlename = "Affair", lastname = "Master", value = 4 }
};
var data = listName
.Where(x => x.value != 0)
.GroupBy(x => (x.firstname, x.middlename, x.lastname))
.ToDictionary(x => x.Key, x => x.ToList());
var myfirstname = "David";
var mylastname = "Broom";
var matchingPeople = data.Where(x => x.Key.firstname == myfirstname && x.Key.lastname == mylastname).SelectMany(x => x.Value);
You need to use .Where(...)
to filter the data, and .Select(...)
to select the .Value
part of the dictionary. Because .Value
is a list, the result would be a List
of List
so use .SelectMany
instead of .Select
to aggregate these List
into a single list
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.