Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use the same foreach code for 2 collections?
    primarykey
    data
    text
    <p>I have 2 collections of 2 different types but have almost the same set of fields. in one function, I need to iterate through one of the collections depending on one condition. I want to write only one code block that will cover both cases. Example: I have the following code:</p> <pre><code>if (condition1) { foreach(var type1var in Type1Collection) { // Do some code here type1var.Notes = "note"; type1var.Price = 1; } } else { foreach(var type2var in Type2Collection) { // the same code logic is used here type2var.Notes = "note"; type2var.Price = 1; } } </code></pre> <p>Now: I want to simplify this code to use the same logic only once ( as they are identical ), something like the following ( P.S : I know the following code is not correct, I am just explaining what I want to do ):</p> <pre><code>var typecollection = Condition1 ? Type1Collection : Type2Collection; foreach(var typevar in TypeCollection) { // the same code logic is used here typevar.Notes = "note"; typevar.Price = 1; } </code></pre> <p>The definition of Type1 &amp; Type2 is similar to the following code ( Actually they are Entity objects):</p> <pre><code> public class Type1 : EntityObject { public int Type1ID { get; set; } public int Type1MasterID { get; set; } public String Notes { get; set; } public decimal Price { get; set; } } public class Type2 : EntityObject { public int Type2ID { get; set; } public int Type2MasterID { get; set; } public String Notes { get; set; } public decimal Price { get; set; } } </code></pre> <p>Update 1:</p> <p>I have included some sample code I am using inside foreach block ( I am accessing a public properties of the 2 types).</p> <p>Update 2:</p> <p>I have included sample Type1 &amp; Type2 definitions, as you can see I have 2 common Public Properties in both classes which I want to update in foreach block.</p> <p>Update 3:</p> <p>I am sorry for the confusion, Type1 &amp; Type2 are derived from EntityObject ( They are both part of my entity model, and the Type1Collection &amp; Type2Collection are actually EntityCollection of these 2 entities.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload