有没有办法将这两个 LINQ 语句组合在一起

本文关键字:两个 LINQ 语句 在一起 组合 有没有 | 更新日期: 2023-09-27 18:33:40

>我有以下内容:

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()

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

有没有办法将这两个 LINQ 语句组合在一起

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

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();