Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the most efficient way to merge items with the same type in a generic list in C#?
    primarykey
    data
    text
    <p><strong>Example, I have the following interface and classes:</strong></p> <pre><code>public interface IRole { DateTime Since {get;} DateTime Until {get;} } public class Manager : IRole { public DateTime Since {get; private set;} public DateTime Until {get; private set;} } public class Employee : IRole { public DateTime Since {get; private set;} public DateTime Until {get; private set;} } public class Ceo: IRole { public DateTime Since {get; private set;} public DateTime Until {get; private set;} } </code></pre> <p><strong>If a generic list contains the following items:</strong></p> <pre><code>list[0]=new Manager(); list[1]=new Manager(); list[2]=new Employee(); list[3]=new Manager(); list[4]=new Ceo(); list[5]=new Ceo(); </code></pre> <p><strong>And I shall merge the same types, combine the Since/Until and shrink the items in list, so the output becomes:</strong></p> <pre><code>newList[0]=new Manager() //(Since is from list[0], Until is from list[1]) newList[1]=new Employee() //(list[2]) newList[2]=new Manager() //(list[3]) newList[3]=new Ceo() //(Since is from list[4], Until is from list[5]) </code></pre> <p><em>Please make sure you understand the question before answering as I have a history of being ambigous and I don't want to upset people. So please comment if you feel the "requirement" isn't clear.</em></p> <p><strong>My way is kind of dumb:</strong></p> <pre><code>for each item in list the current item shall always be merged into the previous item check if current item has the same type as the previous item get last item from newList and merge last item with current item </code></pre> <p>I was just wondering there must be a better solution.</p> <p><strong>Updated:</strong></p> <p>I just realize my "dumb solution" won't cover cases like more than 2 continuous items with the same type.</p> <p>Example: </p> <pre><code>list[0]=new Manager(); list[1]=new Manager(); list[2]=new Employee(); list[3]=new Manager(); list[4]=new Ceo(); list[5]=new Ceo(); list[6]=new Ceo(); </code></pre>
    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