Jeff
Jeff

Reputation: 36573

ICombinable .NET Interface

I'm finding myself in need of "combining" several instances of the same type. This type has several IList properties on it. I want to take each instance and combine the values of those IList properties across the instances, so my code only needs one of those instances.

I'm thinking of creating an ICombinable interface, but I'm wonder if there's something already out there that's suited to this?

   public interface ICombinable<T>
    {
        void CombineWith(T instance);
    }

Upvotes: 1

Views: 235

Answers (3)

Dominic Zukiewicz
Dominic Zukiewicz

Reputation: 8464

Have you tried looking at System.Collections.Generic.HashSet<T>? If you add the same thing multiple times, only 1 item exists.

Upvotes: 1

Jeff
Jeff

Reputation: 36573

I ended up using SelectMany and Select for this. IConfiguration is an interface for the MyConfigurationInfo class. GetMyConfigurationSources returns all the different IConfigurations (from files, DB, etc).

    // accumulates an enumerable property on IConfiguration
    public static IEnumerable<TValue> GetConfigurationValues<TValue>(Func<IConfiguration, IEnumerable<TValue>> selector)
    {
        // cast included for clarification only
        return (GetMyConfigurationSources() as IEnumerable<IConfiguration>)
            .Where(c => selector(c) != null)
            .SelectMany(selector);
    }

    // accumulates a non enumerable property on IConfiguration
    public static IEnumerable<TValue> GetConfigurationValues<TValue>(Func<IConfiguration, TValue> selector)
    {
        // cast included for clarification only
        return (GetMyConfigurationSources() as IEnumerable<IConfiguration>)
            .Where(c => selector(c) != null)
            .Select(selector);
    }

    // Example usage:
    static void Main()
    {
        string[] allEnumerableValues = GetConfigurationValues(c => c.SomeEnumerableConfigPropertyOfStrings);
        string[] allNonEnumerableValues = GetConfigurationValues(c => c.SomeNonEnumerableConfigPropertyString);
    }

Upvotes: 0

Matt Mills
Matt Mills

Reputation: 8792

Sounds like you need Concat

var configs = dbConfig.configList.Concat(fileConfig.configList);

Upvotes: 0

Related Questions