获取列表中没有评级的下一个项目

时间:2015-11-20 09:31:35

标签: c# .net

我有那个班:

public class PhotoRate
{
    public int PhotoRateId { get; set; } // in database this is primary key, autoincrement
    public int PhotoId { get; set; }
    public int? Rate { get; set; }
}

类的对象列表:

private static List<PhotoRate> photoRates = new List<PhotoRate>
{
    new PhotoRate
    {
        PhotoRateId = 5,
        PhotoId = 124,
        Rate = 3
    },
    new PhotoRate
    {
        PhotoRateId = 7,
        PhotoId = 124,
        Rate = null
    },
    new PhotoRate
    {
        PhotoRateId = 16,
        PhotoId = 126,
        Rate = 5
    },
    new PhotoRate
    {
        PhotoRateId = 23,
        PhotoId = 127,
        Rate = null
    }
};

我想要这样的内容:我提供PhotoRateId并获得PhotoRateId的{​​{1}}未评级(评分为空)或如果所有PhotoRate个对象都被评级,则为null。

我有那个算法,但也许你可以告诉我更好的解决方案?

PhotoRate

3 个答案:

答案 0 :(得分:1)

我认为您可以使您的算法更容易,如下所示:

private static int? GetNextPhotoRateId(int photoRateId)
{
    var result = photoRates
        // We check if there are Ids bigger than the one received as parameter
        // in this case we just take the records having PhotoRateId bigger than the id received as parameter
        .Where(pr => photoRates.Any(p => p.PhotoRateId > photoRateId) ? pr.PhotoRateId > photoRateId: true)
        // And with Rate null
        .Where(pr => pr.Rate == null)
        // Select just the PhotoRateId
        .Select(pr => pr.PhotoRateId)
        // Order the result by Id
        .OrderBy(pr => pr)
        // Then take the first (the next one after the Id passed as parameter) 
        // or the default value (0)
        .FirstOrDefault();
    // If the result was 0, then return null
    if (result == 0) return null;
    // Otherwise return the result
    return result;
}

答案 1 :(得分:0)

这个怎么样;

@MBean

编辑:使用 private int? GetNextPhotoRateId(int photoRateId) { //Check all photoRates have rated if (photoRates.Count(x => x.Rate == null).Equals(0)) return null; //Get next photorateid of non rated photorate PhotoRate photoRate = photoRates.FirstOrDefault(x => x.PhotoRateId > photoRateId && x.Rate == null); return photoRate == null ? photoRateId ://no higher id photoRate.PhotoRateId; } 代替FirstOrDefault因为First返回序列的第一个元素,如果没有找到元素,则返回默认值。仅在源为null时才引发异常。当您知道或期望序列至少有一个元素时,请使用FirstOrDefault。 (在你的情况下First是合适的,因为你期望的条件并不总是会发生。)您无需拨打FirstOrDefaultWhere即可使用一个Count拨打电话。

答案 2 :(得分:0)

可以在一行中完成:

// assuming you haven't overwritten default(PhotoRate). If the list is guaranteed to be in order, the OrderBy can be removed. Uses C# 6
private static int? GetNextPhotoRateId(int photoRateId)
{
    return photoRates.Where(p=>p.Rate == null && p.PhotoRateId >photoRateId).OrderBy(p=>p.PhotoRateId).FirstOrDefault()?.PhotoRateId;
}