Linq Lambda groupby和投影问题 [英] Linq Lambda groupby and projection problem

查看:84
本文介绍了Linq Lambda groupby和投影问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一些数据,例如: 型号型号名称代码 阿里斯1.2 1 阿里斯1.3 2 花冠1.1 3 花冠1.4 4

If I have some data like: Model ModelName Code Aris 1.2 1 Aris 1.3 2 Corolla 1.1 3 Corolla 1.4 4

我想用新的投影创建一个groupby查询,例如:

I would like to create a groupby query with a new projection something like:

var vehicles = _vehicleRepository.GroupBy(x=>new {x.Model,x.ModelName,x.Code})
                    .Select(g => new { Text = g.Key.Model + " - " + g.Key.ModelName, g.Key.Code })
                    .ToList();

似乎我在处理Text = g.Key.Model +-" + g.Key.ModelName时遇到困难,并且会导致SQL错误

It seems I am having difficulty with the Text = g.Key.Model + " - " + g.Key.ModelName and it causes SQL errors

任何提示都赞赏

推荐答案

最简单的解决方法可能只是在客户端执行串联:

The simplest fix for this may simply be to perform the concatenation at the client instead:

var vehicles = _vehicleRepository.GroupBy(x => new {x.Model,x.ModelName,x.Code})
                .Select(g => g.Key)
                .AsEnumerable()
                .Select(k => new { Text = k.Model + " - " + k.ModelName, 
                                   k.Code })
                .ToList();

此处AsEnumerable有效地使其余查询仅在.NET中的调用站点上运行.我提供了一个额外的投影,可以 just 从每个组中获取密钥,以便传输的数据不会超出必要的数量.

Here the AsEnumerable effectively makes the rest of the query just run at the call site, in .NET. I've included an extra projection to just get the key from each group, so that no more data is transferred than necessary.

另一种选择可能是使用Distinct:

Another option might be to use Distinct:

var vehicles = _vehicleRepository.Select(x => new {x.Model,x.ModelName,x.Code})
                .Distinct()
                .AsEnumerable()
                .Select(k => new { Text = k.Model + " - " + k.ModelName, 
                                   k.Code })
                .ToList();

您可能不需要此处的AsEnumerable调用-您当然可以尝试将其删除.

It's possible that you don't need the call to AsEnumerable here - you could certainly try removing it.

这篇关于Linq Lambda groupby和投影问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆