我正在使用数据库。我想获取所有消息并根据<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
<h1>{{print()}}</h1>
</div>
对它们进行分组(1个会话包含具有相同RoomId
的消息)。
我试过这个:
RoomId
输出:
我想内联部分:
public class Message
{
public string SenderId { get; set; }
public string ReceiverId { get; set; }
public string RoomId { get; set; }
}
class Program
{
static void Main()
{
var list = new List<Message>
{
new Message { SenderId = "Sender1", ReceiverId = "Receiver1", RoomId = "Room2" },
new Message { SenderId = "Sender1", ReceiverId = "Receiver1", RoomId = "Room1" },
new Message { SenderId = "Sender1", ReceiverId = "Receiver1", RoomId = "Room3" },
new Message { SenderId = "Sender1", ReceiverId = "Receiver1", RoomId = "Room1" },
new Message { SenderId = "Sender1", ReceiverId = "Receiver1", RoomId = "Room2" },
new Message { SenderId = "Sender1", ReceiverId = "Receiver1", RoomId = "Room3" }
};
var group_list = list.GroupBy(x => x.RoomId);
var output_list = new List<List<Message>>();
foreach (var item in group_list)
{
output_list.Add(item.ToList());
}
foreach (var item in output_list)
{
Console.WriteLine($"Conversation {output_list.IndexOf(item) + 1}");
foreach (var msg in item)
{
Console.WriteLine($"SenderId: {msg.SenderId}\tReceiverId: {msg.ReceiverId}\tRoomId: {msg.RoomId}");
}
Console.WriteLine();
}
}
}
为:
foreach (var item in group_list)
{
output_list.Add(item.ToList());
}
我该怎么做?
答案 0 :(得分:4)
在GroupBy
之后,您选择了IEnumerable<Message>
的群组,因此您可以使用ToList
:
List<List<Message>> output_list = list
.GroupBy(x => x.RoomId)
.Select(g => g.ToList())
.ToList();