简体   繁体   中英

mvc razor linq statement which is including firstordefault and where clause

I would like to know if its possible to fix this statement:

@Model.OrdinalDataList.Where(s =>s.CompetitorId == c.Id).Select(x => x.TotalScore).FirstOrDefault()

For example, I have a list of 50 objects, and each 5 objects have the same ID.

I want to get the TotalScore value from one of them from each 5 objects that have the same value for TotalScore for each ID.

Using FirstOrDefault gives me the first value in the collection no matter what the ID of the competitor is.

So my question is, what am I missing here to make this statement work correctly.

If I'm understanding the question correctly, I think what you want is Distinct instead of the Where and the Select and no FirstOrDefault on the end.

@Model.OrdinalDataList.Distinct().Select(x => x.TotalScore)

NOTE: untested!

If that doesn't work because there are more properties in the objects, then you might need to do a Select before the Distinct to get a projection of just the ID and TotalScore properties and then do the final Select to get just the TotalScore .

我对为什么您的列表中有5次相同的数据感到困惑,但这应该获得列表中第一项具有匹配竞争对手ID的TotalScore:

var score = @Model.OrdinalDataList.FirstOrDefault(s => s.CompetitorId == c.Id).TotalScore;

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.

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