Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Using Yield Return to mass copy a Class instance
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Product { public string Name {get;set;} public int Price {get;set;} public string Type {get;set;} public Product ShallowCopy() { return (Product) this.MemberwiseClone(); } } public class Program { public static IEnumerable<Product> Products(int number, Product source) { for (int i = 0; i < number; i++) { // This returns an instance with non-reference type properties yield return source.ShallowCopy(); } } public static void Main(string[] args) { //Your code goes here Console.WriteLine("Use-Case Scenario:"); Console.WriteLine("A customer submits information on the details of 100 products they want created"); Console.WriteLine("All of the products will have the same type, and price, but each will need to be named afterword"); Console.WriteLine("How do i take a instance of information and mass clone it?"); //Our sample object Product Submitted = new Product(){ Price = 50, Type = "Home Furnishings" }; // My fancy way of calling a method that makes 100 shallows copys of the sample object IEnumerable<Product> ProductEnumerator = Products(100,Submitted); //you cant view the index of an IEnumerable //Console.WriteLine(ProductEnumerator[59]); //but you can see its size //Console.WriteLine(ProductEnumerator.Count()); /*explanation: It's not stored. It represents the ability to obtain the data at a later point in time, but the data itself is still lurking in the original collection(s) from which the linq query has been composed. https://stackoverflow.com/questions/43629498/linq-ienumerablet-memory-structure/43629578 */ // Adding all the objects we created into a list List<Product> ProductList = new List<Product>(); foreach(Product i in ProductEnumerator) { // this is where the IEnumerable is enumerated and added to the ProductList, thus loading it into memory (twice, once to the ienumerable, and then to to ProductList ProductList.Add(i); } Console.WriteLine("ProductList now has {0} items!",ProductList.Count()); Console.WriteLine("And to prove they are independent of eachother..."); ProductList[0].Name = "Chair"; ProductList[1].Name = "Tv Stand"; Console.WriteLine(ProductList[0].Name); Console.WriteLine(ProductList[1].Name); } } }
run
|
edit
|
history
|
help
0
Tarkov Time
code
sorted array
Test equality...1
Binary search tree - Pre-order Traversal
rekenmachine in c#
QQW
Main3
Random number string changer
Qwe