我有日志 - 可以是两种类型的动作列表:呼叫和消息。 我需要使用LINQ获取大多数已接收呼叫和消息的5个号码。对于发送这些操作的数字也是如此。
class Action
{
public static int Id { get; }
public int Sender { get; }
public int Receiver { get; }
public OperationTypes Type { get; }
public string MessageText { get; }
public Action(int sender, int receiver, OperationTypes type, string message = "")
{
Id++;
Sender = sender;
Receiver = receiver;
Type = type;
MessageText = (type == OperationTypes.Message) ? message : string.Empty;
}
问题是关于我需要将呼叫计为1并将消息计为0.5的事情,并计算此结果的总和。
var accounts = _journal
.Select(x => new {x.Receiver, x.Type})
.GroupBy(x => x.Receiver)
.OrderByDescending(x => x.Count())
.Take(5);
不知道如何使用LINQ正确地执行此操作并将消息计为0.5 *调用。
答案 0 :(得分:1)
上面的Aluan Haddad's提示,请尝试添加计算的Value
属性:
class Action
{
...
public double Value => Type == OperationTypes.Message ? 0.5 : 1.0;
}
然后在您的匿名类型中使用Value
,并将其加总,而不是计入您的OrderByDescending
来电:
var accounts = _journal
.Select(x => new { x.Receiver, x.Value })
.GroupBy(x => x.Receiver)
.OrderByDescending(x => x.Sum(action => action.Value))
.Take(5);