1

我有以下代码。该函数有很多 Linq 调用,我在将其落实到位时得到了帮助。

    public IList<Content.Grid> Details(string pk)
    {
        IEnumerable<Content.Grid> details = null;
        IList<Content.Grid> detailsList = null;
        var data = _contentRepository.GetPk(pk);
        var refType = this.GetRefType(pk);
        var refStat = this.GetRefStat(pk);
        var type = _referenceRepository.GetPk(refType);
        var stat = _referenceRepository.GetPk(refStat);
        details =
        from d in data
        join s in stat on d.Status equals s.RowKey into statuses
        from s in statuses.DefaultIfEmpty()
        join t in type on d.Type equals t.RowKey into types
        from t in types.DefaultIfEmpty()
        select new Content.Grid
        {
            PartitionKey = d.PartitionKey,
            RowKey = d.RowKey,
            Order = d.Order,
            Title = d.Title,
            Status = s == null ? null : s.Value,
            StatusKey = d.Status,
            Type = t == null ? null : t.Value,
            TypeKey = d.Type,
            Link = d.Link,
            Notes = d.Notes,
            TextLength = d.TextLength
        };
        detailsList = details
                .OrderBy(item => item.Order)
                .ThenBy(item => item.Title)
                .Select((t, index) => new Content.Grid()
                {
                    PartitionKey = t.PartitionKey,
                    RowKey = t.RowKey,
                    Row = index + 1,
                    Order = t.Order,
                    Title = t.Title,
                    Status = t.Status,
                    StatusKey = t.StatusKey,
                    Type = t.Type,
                    TypeKey = t.TypeKey,
                    Link = t.Link,
                    Notes = t.Notes,
                    TextLength = t.TextLength,

                })
                 .ToList();
        return detailsList;

    }

第一个对 Linq 使用一种格式,第二个使用另一种格式。有什么方法可以简化和/或组合这些吗?我真的很想让这段代码更简单,但我不知道该怎么做。任何建议将不胜感激。

4

1 回答 1

1

当然,您可以将它们组合在一起。Linq 关键字(例如from,whereselectget 转换为您在下面调用的 Extension 方法之类的调用,因此实际上没有区别。

如果您真的想组合它们,最快的方法是()绕过第一个查询,然后附加您details在第二个查询中使用的方法调用。像这样:

detailsList =
        (from d in data                    // <-- The first query
         // ...
         select new Content.Grid
         {
             // ...
         })
         .OrderBy(item => item.Order)    // <-- The calls from the second query
         .ThenBy(item => item.Title)
         .Select((t, index) => new Content.Grid()
         {
             //...
         }).ToList();

But i think that would be ugly. Two queries are just fine IMO.

于 2012-05-31T07:25:52.450 回答