I want to use LINQ to get the maximum value of properties for a class in a dictionary within a class.

Asked 1 years ago, Updated 1 years ago, 104 views

I'm always studying.I'd like to borrow your advice today. Let me ask you a question.

public class TestResult{
    public string Kamoku;
    public int Tensu;
}

public class Grade {
    public int Rank;
    public List <TestResult>result;
}

public class Peron {
    public int Id;
    public string name;
    public Dictionary <string, Grade >dic;
}

If there is a class like the one above, I would like to get the maximum value of Tensu, but how can I write it briefly?

PersonalData = new Person() for each property or dictionary
Assume you have already configured the value, but

int MaxTensu=personalData.dic.Values.Max(x=>x.result.Max(y=>y.Tensu));

In this way of writing, an error occurred when "Elements in sequence do not contain elements".
↓ Should it be written in such a way?Thank you for your cooperation.

int max=0;
foreach (Grade in personalData.dic.Values) {
    inti=g.result.Max(x=>x.Tensu);
    if(max<i){
        max = i;
    }
}

c# linq

2022-09-30 14:59

2 Answers

(Apart from execution efficiency) I don't think it's wrong, but the Max requires at least one element, so if the element dic or result is empty, such an error occurs.

Once flattened with SelectMany, it will be OK if there is even one result element anywhere.

int max=personalData.dic.Values.SelectMany(g=>g.result).Max(r=>r.Tensu);

If dic is empty or all result is empty, you can enter the default value in DefaultIfEmpty.

int max=personalData.dic.Values.SelectMany(g=>g.result)
    .Select(r=>r.Tensu).DefaultIfEmpty(0).Max();


2022-09-30 14:59

Enumerable.Max does not cause exceptions when you use Nullable<T> type overload, so you can cast it to int?.

int?MaxTensu=personalData.dic.Values.Max(x=>x.result.Max(y=>(int?)y.Tensu));

If you add ?0 at the end, 0 is the default value.


2022-09-30 14:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.