【发布时间】:2011-01-01 02:55:41
【问题描述】:
我有这门课:
public class ItemList
{
public int GuID { get; set; }
public int ItemID { get; set; }
public string Name { get; set; }
public entityType Status { get; set; }
public int Zone { get; set; }
public class Waypoint
{
public int SubID { get; set; }
public int Heading { get; set; }
public float PosX { get; set; }
public float PosY { get; set; }
public float PosZ { get; set; }
}
public List<Waypoint> Routes = new List<Waypoint>();
}
在此列表中使用: public List myList = new List();
新添加的项目是这样的:
ItemList newItem = new ItemList();
newItem.GUID = GUID;
newItem.ItemID = ItemID;
newItem.Name = Name;
newItem.Status = Status;
// Inner Routes List
ItemList.Waypoint itemLocation = new ItemList.Waypoint();
itemLocation.SubID = SubID;
itemLocation.Zone = Zone;
itemLocation.Heading = convertHeading(Heading);
itemLocation.PosX = PosX;
itemLocation.PosY = PosY;
itemLocation.PosZ = PosZ;
itemLocation.Rest = Rest;
newItem.Routes.Add(itemLocation);
myList.Add(newItem);
现在我需要按 ItemID 对其进行分组,并加入每个相同 ItemID 的 Routes 的第一个条目。
这将是public List<ItemList> myList = new List<ItemList>(); 数据的示例:
GUID ItemID ListOfRoutes
1 20 GUID_1_Routes
2 20 GUID_2_Routes
3 20 GUID_3_Routes
4 20 GUID_4_Routes
5 20 GUID_5_Routes
6 55 GUID_6_Routes
7 55 GUID_7_Routes
8 55 GUID_8_Routes
9 1 GUID_9_Routes
10 1 GUID_10_Routes
您可以看到 GUID 是唯一的,ItemID 可以自我重复。 每个 GUID 都有一个路由列表,所有路由列表至少有 1 个及以上条目。
Routes 是 ItemList public List<Waypoint> Routes = new List<Waypoint>(); 类的一部分
路线示例。
GUID_1_Routes 有:
Entry Zone SubID Heading PosX PosY PosZ
1 1200 0 100 1029.32 837.21 29.10
2 1200 0 120 1129.32 537.21 29.10
3 1200 0 180 1229.32 137.21 29.10
4 1200 0 360 1329.32 437.21 29.10
5 1200 0 100 1429.32 637.21 29.10
GUID_2_Routes 有:
Entry Zone SubID Heading PosX PosY PosZ
1 100 0 10 129.32 437.21 29.10
所以我想要做的是我在 myList 上按 ItemID 分组的所有条目的列表,维护字段 ItemID 和 Name ... 以及每个 ItemID 的新列表,它将存储来自每个 GUID 的每个路由的第一个元素具有相同的 ItemID。
例如 ItemID 20 将产生以下结果:
ItemID、名称、ListOfRoutes
这个 ItemID ListOfRoutes 将包含
GUID_1_Routes 第一个条目:
Entry Zone SubID Heading PosX PosY PosZ
1 1200 0 100 1029.32 837.21 29.10
GUID_2_Routes 第一个条目:
Entry Zone SubID Heading PosX PosY PosZ
1 100 0 10 129.32 437.21 29.10
GUID_3_Routes、GUID_4_Routes、GUID_5_Routes 第一个条目。
更新 2:
这就是我设法获得我想要的结果的方式,但我仍然相信通过单个查询或以比我目前使用的更好的方式可以实现:
var query = from ItemList item in myList
where status.Contains(item.Status)
group item by new
{
item.ItemID,
item.Name,
item.Zone
}
into newList
orderby newList.Key.ItemID ascending
select new
{
newList.Key.ItemID,
newList.Key.Name,
newList.Key.Zone
};
foreach (var thisItem in query)
{
var location = from n in myList
where n.ItemID == thisItem.ItemID
select new
{
Routes = n.Routes.First()
};
foreach (var thisObject in location)
{
ItemList.Waypoint thisRoutes = thisObject.Routes;
}
}
【问题讨论】:
标签: c# linq containers