Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# generic with supplied parameter names

I’m trying to create a generic function that can take a list of objects with start-datetime and end-datetime and combine the if they’re right after one another wit no gaps between.

        public static IEnumerable<T> MakeBlocks<T>(IEnumerable<T> input)
        {
            List<T> outList = new List<T>();
            if (input.Count() == 0) return outList;

            T thisEntry = input.First();
            foreach (var nextEntry in input.Skip(1))
            {
                if ( nextEntry != null && nextEntry.StartDT == thisEntry.EndDT)
                {
                    thisEntry.EndDT = nextEntry.EndDT;
                }
                else
                {
                    outList.Add(thisEntry);
                    thisEntry = nextEntry;
                }
            }
            outList.Add(thisEntry);

            return outList;
        }

This works fine if I know what the "From" and "to" property is called, but how can I do this with a generic?
The "unknown" properties in the above pseudo-example is called StartDT and EndDT, but thay could be called anything.

In JavaScript I can just supply the the property name as a string, but that won’t do in c#.
Is this possible and how?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use generic constraints. So you would have a class that all your T’s inherit from. Like so:

Modified method to use generic constarint

public static IEnumerable<T> MakeBlocks<T>(IEnumerable<T> input) where T : SomeClass
{
    List<T> outList = new List<T>();
    if (input.Count() == 0) return outList;

    T thisEntry = input.First();
    foreach (var nextEntry in input.Skip(1))
    {
        if (nextEntry != null && nextEntry.StartDT == thisEntry.EndDT)
        {
            thisEntry.EndDT = nextEntry.EndDT;
        }
        else
        {
            outList.Add(thisEntry);
            thisEntry = nextEntry;
        }
    }
    outList.Add(thisEntry);

    return outList;
}

Base class that all your T’s should inherit from

public abstract class SomeClass
{
    public DateTime EndDT { get; set; }
    public DateTime StartDT { get; set; }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading