Bohn
Bohn

Reputation: 26919

Combining two list variables into one operation

What I have that I start with is three string variables for example

string myVar1 = "hi";
string myVar2 = "bye";
string myVar3 = "who dis";

CURRENTLY I am doing this, It "works" but I feel like there is redundancy:

    List<string> listOne= new List<string>
    {
        myVar1 , myVar2,myVar3 
    };
    listOne= listOne.Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => t).ToList();

    var whatIFinallyWantToHave= new HashSet<string>(listOne, StringComparer.OrdinalIgnoreCase);

I am thinking there should be a way to get rid of listOne and do it in one go. Do you know how? ( note we still need to ignore the empty or null strings that listOne is cleaning.)

Upvotes: 1

Views: 336

Answers (2)

NetMage
NetMage

Reputation: 26927

There is no reason to create a List or have a separate variable, but you have to combine the individual values somehow. Also, there is no reason to create (yet) another List just because you are filtering.

string myVar1 = "hi";
string myVar2 = "bye";
string myVar3 = "who dis";

var whatIFinallyWantToHave = new[] { myVar1, myVar2, myVar3 }
                             .Where(s => !String.IsNullOrWhiteSpace(s))
                             .ToHashSet(StringComparer.OrdinalIgnoreCase);

NOTE: This requires .Net 4.7.2 for the ToHashSet method.

Upvotes: 1

ChiefTwoPencils
ChiefTwoPencils

Reputation: 13940

I think it's worth adding an extension in this case so you can chain from the list to the set directly. This way you don't have to break the flow to explicitly construct the hash set. Perhaps:

public static class Extensions
{
    public static HashSet<T> ToHashSet<T>(
        this IEnumerable<T> source,
        IEqualityComparer<T> comparer = null)
    {
        return new HashSet<T>(source, comparer);
    }
}

And use it like so:

string myVar1 = "hi";
string nully = null;
string myVar2 = "bye";
string empty = "";
string myVar3 = "who dis";
string dup = "WHO DIS";

List<string> listOne = new List<string>
{
    nully, myVar1, empty, myVar2 ,myVar3, dup
};

listOne
    .Where(t => !string.IsNullOrWhiteSpace(t))
    .ToHashSet(StringComparer.OrdinalIgnoreCase)
    .ToList()
    .ForEach(Console.WriteLine);
// hi
// bye
// who dis

Upvotes: 1

Related Questions