简体   繁体   English

来自 ObservableCollection 的 Linq 最大值

[英]Linq Max Value from ObservableCollection

I have an ObservableCollection with two properties string and int.我有一个 ObservableCollection,它有两个属性 string 和 int。 I would like to query and return the int with the Max value.我想查询并返回具有最大值的 int。

Data example:数据示例:

Category, WorkOrderVersion类别,工单版本

AAA 1 AAA 1

AAA 2 AAA 2

AAA 3 AAA 3

BBB 1 BB 1

BBB 2 BBB 2

if Category == "BBB" I would want to return 2如果 Category == "BBB" 我想返回 2

This is kind of what I mean:这就是我的意思:

var maxWorkOrderVersion = WorkOrderDetailsObsCollection.Where(x=>x.Category == firstSelection.Category) return Max(WorkOrderVersion);`

If you just want to get the largest WorkOrderVersion for the selected Category , then you can return it using Max :如果您只想获得所选Category的最大WorkOrderVersion ,则可以使用Max返回它:

int maxWorkOrderVersion = WorkOrderDetailsObsCollection
    .Where(x => x.Category == firstSelection.Category)
    .Max(x => x.WorkOrderVersion);

Otherwise, if you want the whole object for the specified Category that has the largest WorkOrderVersion , then you can order your list by the property (after filtering for the Category ), and select the FirstOrDefault one (the default value of null would be returned in the case where no items of the specified Category exist):否则,如果您想要具有最大WorkOrderVersion的指定Category的整个对象,那么您可以按属性对您的列表进行排序(在过滤Category ),并选择FirstOrDefault一个( null的默认值将在不存在指定Category项目的情况):

var maxWorkOrderVersion = WorkOrderDetailsObsCollection
    .Where(x => x.Category == firstSelection.Category)
    .OrderByDescending(x => x.WorkOrderVersion)
    .FirstOrDefault();

If you want get notifications when WorkOrderDetailsObsCollection changes or Category property changes, you can use my ObservableComputations library.如果您想在 WorkOrderDetailsObsCollection 更改或 Category 属性更改时收到通知,您可以使用我的ObservableComputations库。 Using that library you can code:使用该库,您可以编码:

var maxWorkOrderVersion = WorkOrderDetailsObsCollection
    .Filtering(x=> x.Category == firstSelection.Category)
    .Selecting(x => x.WorkOrderVersion)
    .Maximazing();

// maxWorkOrderVersion.Value is what you need

maxWorkOrderVersion is INotifyPropertyChanged . maxWorkOrderVersion 是INotifyPropertyChanged Actual value is stored in Value property.实际值存储在 Value 属性中。 Ensure that properties mentioned in the code above notify of changes through the INotifyPropertyChanged interface.确保上面代码中提到的属性通过INotifyPropertyChanged接口通知更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM