匿名类型的集合?类型

2023-09-04 00:32:09 作者:狂起来没完

我要寻找的最佳实践创建匿名类型进行的募款活动。

I am looking for best practices for creating collections made from anonymous types.

有几种方法 - 这之一,大多数的答案在这个螺纹假设整个匿名收集可以在一条语句来构建。

There are several approaches - this one and most answers on this thread assume that the whole anonymous collection can be constructed in one statement.

作为匿名类型通常用于替换类要被用来存储临时(如提出在this SO回答),我想,以避免创建和使用类匿名收藏,为的这个帖子建议。

As anonymous types are usually used to replace classes that are to be used to store temporary (as put forward in this SO answer), I would like to avoid creating and using a class for anonymous collections, as this post suggests.

在我的情况,我遍历集合 - 对于集合中的每个项目我想收集相关对象在一个匿名类型(作为一个元组)。我需要这些匿名类型被放在一个集合,然后对其进行排序为进一步开展工作。

In my case, I am iterating over a collection - for each item in the collection I would like to collect related objects in an anonymous type (acting as a tuple). I need these anonymous types to be put in a collection and then sort them for further work.

其他的方法我已经考虑:

Other approaches I have considered:

使用一个Object []或ArrayList中(失去匿名类型的利益) 创建为必需项目的包装类(不再需要匿名类型)

这是我在code中的唯一的地方,我需要这样一个集合 - 这将是最好的办法。

This is the only place in my code that I need such a collection - what would be the best approach?

补充说明:

我正与传统的.NET 1.1中的对象,所以我有工作的集合是强类型集合实现IEnumerable的,因此大多数的LINQ扩展方法等。选择是行不通的:

I am working with legacy .Net 1.1 objects, so the collections I am working with are strongly typed collections implementing IEnumerable, and as such most Linq extension methods such as .Select won't work:

code样品

foreach (Item item in myItems)
{
	foreach (Confirmation confirmation in item.GetConfirmations(true))
	{
		if (lastParentId != item.ParentId)
		{
			lastParentId = item.ParentId;
			parentObject = new ParentItem(lastParentId);
		}

		itemHolder = new ArrayList { item, confirmation };
		if (parentObject!= null)
		{
		    itemHolder.Add(parentObject.Rate);
		}

    	sortConfirmations.Add(confirmation.Date, itemHolder);
    }
}

// Use sortConfirmations

分辨率

我结束了使用一个通用的字典,收集相关的物品放在一起,并使用.OrderBy()对它们进行排序 - 丑陋,但它的工作原理......而且比现有code更好

I ended up using a generic dictionary to collect the related items together and using .OrderBy() to sort them - ugly, but it works... and is better than the existing code.

推荐答案

对于一个非常不同的答案...... LINQ?

For a very different answer... LINQ?

在我的情况,我遍历一个   收集 - 在每个项目   收藏我要收藏   在一个匿名类型相关对象   (作为一个元组)。我需要这些   匿名类型被放在一个   集合,然后排序他们   进一步的工作。

In my case, I am iterating over a collection - for each item in the collection I would like to collect related objects in an anonymous type (acting as a tuple). I need these anonymous types to be put in a collection and then sort them for further work.

这听起来像:

var list = (from item in collection
          from related in item.Relationship
          order by ...something...
          select new {item,related}).ToList()