LINQ-如果count> 1,则选择两个值中的最大值

时间:2019-02-16 13:02:33

标签: c# asp.net-mvc linq

我有一些LINQ可以带回一些数据。它由两个属性ChannelType和ChannelName组成。有时,由于尚未设置频道,因此频道类型将为null,并且其计数仅为1。

LINQ查询:

var channels = (from channel in db.UriData
                join device in db.Devices on channel.SerialNumber equals device.SerialNumber
                join active in db.ActiveChannels on channel.ChannelName equals active.ChannelName
                where channel.ChannelName.Contains(active.ChannelName) && 
                device.Active &&
                channel.SerialNumber == serial
                select new { channel.ChannelName, channel.ChannelType }).Distinct().ToList().OrderByDescending(x => x.ChannelName);           

LINQ查询返回的数据:

{ ChannelName = "v1", ChannelType = null }
{ ChannelName = "v1", ChannelType = "Electricity" }
{ ChannelName = "v2", ChannelType = null }
{ ChannelName = "v2", ChannelType = "Electricity" }
{ ChannelName = "v3", ChannelType = null }
{ ChannelName = "v3", ChannelType = "Electricity" }
{ ChannelName = "v4", ChannelType = null }

从数据中,您将看到ChannelName有两个值,一个是null,一个不是。我希望能够选择Max()值,因此在有两个通道名称的地方,我可以忽略null。 Max()将处理null的单个ChannelName,如数据中的第一项所示。

如何选择Max()并删除多个ChannelName的空值。例如,如果我们使用数据中所示的ChannelName v1,则可以看到有两个v1。我想获取Max()并忽略/删除存在多个v1的null值。

我假设我可以通过另一个LINQ查询来做到这一点,例如:

var c = channels.Select(x => new { x.ChannelName, x.ChannelType }).Max();

预期结果:

{ ChannelName = "v1", ChannelType = "Electricity" }
{ ChannelName = "v2", ChannelType = "Electricity" }
{ ChannelName = "v3", ChannelType = "Electricity" }
{ ChannelName = "v4", ChannelType = null }

TIA

3 个答案:

答案 0 :(得分:2)

执行此操作的一种方法是使用GroupBy。基本上,您将所有通道按名称(键)分组,然后对所有值进行排序,以获取第一个符合您条件的通道:

var result = channels
    .GroupBy(i => i.ChannelName)
    .Select(i => new 
    { 
        ChannelName = i.Key, 
        ChannelType = i.OrderByDescending(v => v.ChannelType)
                       .First()
                       .ChannelType
    });

答案 1 :(得分:0)

尝试以下操作:

            var results = channels.Where(x => x.ChannelType != null)
                .Select(x => new { index = int.Parse(x.ChannelName.Replace("v", "")), channel = x })
                .GroupBy(x => x.channel.ChannelType)
                .Select(x => x.OrderByDescending(y => y.index))
                .Select(x => x.FirstOrDefault().channel)
                .ToList();

答案 2 :(得分:0)

var _channels = new List<(string, string)>();

foreach(var c in channels)
{
    var channeltypes = channels.Where(x => x.ChannelName == c.ChannelName && x.ChannelType != null);
    if(channeltypes.Any())
    {
        _channels.Add((channeltypes[0].ChannelName, channeltypes[0].ChannelType));
    } else {
        _channels.Add((c.ChannelName, null));
    }
}