这是一个用 C# 编写的程序示例,它输出由 ID 标识的来源、每个来源中可用的产品数量和所选产品(每个来源都附加了来源 ID)作为证明:
using System.Linq;
using System.Collections.Generic;
using System;
namespace ConsoleApplication1
{
class Product
{
public int Ordinal { get; set; }
public Source Source { get; set; }
public Product(int ordinal)
{
Ordinal = ordinal;
}
}
class Source : List<Product>
{
public int Id { get { return this.GetHashCode(); } }
public int AvailableProducts { get { return this.Count; } }
public Source(int availableProducts)
{
for (int i = 0; i < availableProducts; i++)
{
var p = new Product(i);
p.Source = this;
this.Add(p);
}
}
}
class Sources : List<Source>
{
}
class Program
{
static void Main(string[] args)
{
var sources = new Sources();
var productsToBeSelected = 4;
var sourceNumber = Math.Min(productsToBeSelected, 4);
var maxProductsPerSource = 5;
for (int i = 0; i < sourceNumber; i++)
{
var source = new Source((new Random(i + Int32.Parse(DateTime.Now.Ticks.ToString().Substring(DateTime.Now.Ticks.ToString().Length - 6)))).Next(maxProductsPerSource));
sources.Add(source);
}
var candidateProducts=new List<Product>();
sources.ForEach(i=>i.ForEach(p=>candidateProducts.Add(p)));
var selectedProducts = candidateProducts.OrderBy(i => i.Ordinal).Take(productsToBeSelected);
foreach (var item in sources)
{
Console.WriteLine("Source ID: {0}, {1} products",item.Id, item.Count);
}
foreach (var item in selectedProducts)
{
Console.WriteLine("Product ordinal: {0} from source {1}", item.Ordinal , item.Source.Id);
}
}
}
}