次の方法を使用してランダムなProductリストを生成しようとしていますが、同じProductインスタンスを複数回取得しています。
Output for count 5:
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
私は参照型であるリスト型を読みました、そしてそれはものを上書きします。以下は私のコードです。ユニークなProductインスタンスを提供できるものがありませんか?ありがとう&私はあなたの助けをいただければ幸いです。
public List<Product> ProductGroupGenerator(int count)
{
List<Product> pList = new List<Product>();
for (int i = 0; i < count; i++)
{
Random r = new Random();
string alphabet = "abcdefghijklmnopqrstuvwyxzeeeiouea";
Func<char> randomLetter = () => alphabet[r.Next(alphabet.Length)];
Func<int, string> makeName =
(length) => new string(Enumerable.Range(0, length)
.Select(x => x == 0 ? char.ToUpper(randomLetter()) : randomLetter())
.ToArray());
//string last = makeName(r.Next(7) + 7);
//string company = makeName(r.Next(7) + 7) + " Inc.";
string prodName = makeName(r.Next(5) + 5);
int unitsInStock = r.Next(100);
float unitPrice = (float)(r.NextDouble() * 10);
Product p = new Product();
p.Name = prodName;
p.UnitsInStock = unitsInStock;
p.UnitPrice = unitPrice;
pList.Add(p);
p = null;
}
return pList;
}