我是一名从事IT技术的助手,您需要翻译的内容是关于代码库中大量一级集合的使用。为了方便使用LINQ处理这些集合,每个集合都有一个扩展方法,例如:
public static class CustomCollectionExtensions
{
public static CustomCollection ToCustomCollection(this IEnumerable<CustomItem> enumerable)
{
return new CustomCollection(enumerable);
}
}
伴随相应的构造函数:
public class CustomCollection : List<CustomItem>
{
public CustomCollection(IEnumerable<CustomItem> enumerable) : base(enumerable) { }
}
这段代码看起来是样板代码,因此我尝试编写一个通用的
IEnumerable<U>.To<T>()
方法,这样我们就不需要一直生成特定的 ToXCollection() 方法了。我已经完成了以下部分:
public static class GenericCollectionExtensions
{
public static T To<T, U>(this IEnumerable<U> enumerable) where T : ICollection<U>, new()
{
T collection = new T();
foreach (U u in enumerable)
{
collection.Add(u);
}
return collection;
}
}
这需要像这样调用:customCollectionInstance.OrderBy(i => i.Property).To<CustomCollection, CustomItem>()
有没有一种方法可以避免指定CustomItem
类型,以便我们可以使用customCollectionInstance.OrderBy(i => i.Property).To<CustomCollection>()
,或者这不是通用的解决方案?
var a = Member.Offers.ActiveOffers()
看起来比每次都使用 .Where() 更简洁。 - Justin Edwards