C#linq查询所有方法

时间:2015-07-30 13:27:36

标签: c# linq

有一个集合

List<<KeyValuePair<string, Person>>
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int MealType { get; set; }
}

patientEffort.Add("1", new Person() { FirstName = "Raja", LastName = "Ram", MealType = 2 });

patientEffort.Add("2", new Person() { FirstName = "Vijay", LastName = "Anthony", MealType = 1 });
patientEffort.Add("2", new Person() { FirstName = "Vijay", LastName = "Anthony", MealType = 2 });
patientEffort.Add("2", new Person() { FirstName = "Vijay", LastName = "Anthony", MealType = 3 });


patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 1 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 2 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 3 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 4 });
List<int> _listMealType = new List<int>();

如果_listMealType = [2]已通过,则结果将为

{Key: "1", FirstName = "Raja", LastName = "Ram"}
{Key: "2", FirstName = "Vijay", LastName = "Anthony"}
{Key: "3", FirstName = "Dr", LastName = "APJ"}

如果_listMealType = [1,2,3]已通过,则结果将为

 {Key: 2, FirstName = "Vijay", LastName = "Anthony"}
 {Key: 3, FirstName = "Dr", LastName = "APJ"} 

如果_listMealType = [1,2,3,4]已通过,则结果将为

 {Key: "3", FirstName = "Dr", LastName = "APJ"} only

键可能是字符串或int无关紧要。我可以对此方案进行linq查询。我用过All方法是linq但没有用。

var query = patientEffort.Where(d => _listMealType.All(x => x == d.Value.MealType)).Select(d => d.Key);

请您帮我尽快解决查询问题。

1 个答案:

答案 0 :(得分:1)

我希望它有所帮助:

        var patients = patientEffort.GroupBy(x => x.Value.FirstName);
        var result = (from patient in patients let res = patient.Select(note => note.Value.MealType).ToList() where _listMealType.Intersect(res).Count() == _listMealType.Count select patient.First()).ToList();

以下是不使用linq的变体:

        var patients = patientEffort.GroupBy(x => x.Value.FirstName);   // group patients by name
        foreach (var patient in patients)
        {
            var res = new List<int>();
            foreach (var note in patient)  // collect all meal types of current patient
                res.Add(note.Value.MealType);

            if (_listMealType.Intersect(res).Count() == _listMealType.Count)  // if intersection count equal to source meal list - it's our patient.
                result.Add(patient.First());  // add information about patient. because we need only name - we can use first record in list.
        }