1

我有以下内容:

var data = _cityRepository.GetAll(
    u => u.PartitionKey == pk & 
    u.RowKey.CompareTo(lowerBound) >= 0 & 
    u.RowKey.CompareTo(upperBound) < 0);

details =
    from d in data
    select new City.Grid
    {
        PartitionKey = d.PartitionKey,
        RowKey = d.RowKey,
        ShortTitle = d.ShortTitle,
        Created = d.Created,
        Modified = d.Modified,
        ModifiedBy = d.ModifiedBy
    };

detailsList = details
    .OrderBy(item => item.Modified)
    .Select((t, index) => new City.Grid()
    {
        PartitionKey = t.PartitionKey,
        RowKey = t.RowKey,
        Row = index + 1,
        ShortTitle = t.ShortTitle,
        Created = t.Created,
        Modified = t.Modified,
        ModifiedBy = t.ModifiedBy
    })
    .ToList();

对我来说,问题是我不确定如何组合第二个,因为它使用了这个:

Select((t, index) => new City.Grid()

有没有办法可以将这些语句合并为一个,或者如果不可能,我可以将最后两个合并吗?

4

1 回答 1

3

当然 - 这很丑陋,但这三个都有:

var query = _cityRepository.GetAll(
                               u => u.PartitionKey == pk & 
                               u.RowKey.CompareTo(lowerBound) >= 0 & 
                               u.RowKey.CompareTo(upperBound) < 0)
                .Select(d => new City.Grid
                        {
                            PartitionKey = d.PartitionKey,
                            RowKey = d.RowKey,
                            ShortTitle = d.ShortTitle,
                            Created = d.Created,
                            Modified = d.Modified,
                            ModifiedBy = d.ModifiedBy                          
                        }
                .OrderBy(item => item.Modified)
                .Select((t, index) => new City.Grid()
                {
                    PartitionKey = t.PartitionKey,
                    RowKey = t.RowKey,
                    Row = index + 1,
                    ShortTitle = t.ShortTitle,
                    Created = t.Created,
                    Modified = t.Modified,
                    ModifiedBy = t.ModifiedBy
                })
                .ToList();

City.Grid避免两次创建新对象会更明智:

var query = _cityRepository.GetAll(
                               u => u.PartitionKey == pk & 
                               u.RowKey.CompareTo(lowerBound) >= 0 & 
                               u.RowKey.CompareTo(upperBound) < 0)
                .OrderBy(item => item.Modified)
                .Select((t, index) => new City.Grid()
                {
                    PartitionKey = t.PartitionKey,
                    RowKey = t.RowKey,
                    Row = index + 1,
                    ShortTitle = t.ShortTitle,
                    Created = t.Created,
                    Modified = t.Modified,
                    ModifiedBy = t.ModifiedBy
                })
                .ToList();
于 2012-05-10T10:17:38.987 回答