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.

3

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.