0

I have two functions:

public List<string> getAllProperties1()
{
    List<string> output = new List<string>();
    foreach (MyItem item in getItems())
    {
        if (!output.Contains(item.property1) &&
            item.property1 != null)
        {
            output.Add(item.property1);
        }
    }
    return output;
}

public List<string> getAllProperties2()
{
    List<string> output = new List<string>();
    foreach (MyItem item in getItems())
    {
        if (!output.Contains(item.property2) &&
            item.property2 != null)
        {
            output.Add(item.property2);
        }
    }
    return output;
}    

I renamed functions, items and properties to make things more simple. What I want to do is one function, may be even more simple - instead of these two. How to achieve this?

Property1 and Property 2 are both string properties.

demonplus
  • 5,613
  • 12
  • 49
  • 68
  • 2
    Code improvement belongs to [codereview.stackexchange.com/](http://codereview.stackexchange.com/). – Tim Schmelter May 12 '15 at 07:37
  • possible duplicate of [Get property value from C# dynamic object by string (reflection?)](http://stackoverflow.com/questions/8631546/get-property-value-from-c-sharp-dynamic-object-by-string-reflection) – Cwt May 12 '15 at 07:39
  • @TimSchmelter This code has been stripped of context (placeholder names being used instead of the real values) which makes it off-topic as "example code" on CR. – Simon Forsberg May 12 '15 at 10:56

3 Answers3

4

Do you really need methods for this:

List<string> allUniqueProp1 = getItems()
    .Select(x => x.property1)
    .Where(s => s != null)
    .Distinct()
    .ToList();

The same with property2 and you are done

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Code:

public List<string> getAllProperties(Func<MyItem, string> func)
{
    List<string> output = new List<string>();
    foreach (MyItem item in getItems())
    {
        string value = func(item);
        if (!output.Contains(value) &&
            value != null)
        {
            output.Add(value);
        }
    }
    return output;
}

Usage:

getAllProperties(e => e.property1);
General-Doomer
  • 2,681
  • 13
  • 13
1

Use a Func as a strategy to acquire comparison property and call from a single method:

public List<string> GetAll(Func<MyItem, string> propertyGetter)
{
    List<string> output = new List<string>();
    foreach (MyItem item in getItems())
    {
        var value = propertyGetter(item);
        if (!output.Contains(value) && value != null)
        {
            output.Add(value);
        }
    }
    return output;
} 

Then to use:

GetAll(item => item.Property1);
GetAll(item => item.Property2);
James Lucas
  • 2,452
  • 10
  • 15