Search code examples
c#stringcollection

How to generate a unique string from a string collection?


I need a way to convert a strings collection into a unique string. This means that I need to have a different string if any of the strings inside the collection has changed.

I'm working on a big solution so I may wont be able to work with some better ideas. The required unique string will be used to compare the 2 collections, so different strings means different collections. I cannot compare the strings inside one by one because the order may change plus the solution is already built to return result based on 2 strings comparison. This is an add-on. The generated string will be passed as parameter for this comparison.

Thank you!


Solution

  • These both work by deciding to use the separator character of ":" and also using an escape character to make it clear when we mean something else by the separator character. We therefore just need to escape all our strings before concatenating them with our separator in between. This gives us unique strings for every collection. All we need to do if we want to make collections the same regardless or order is to sort our collection before we do anything. I should add that my sample uses LINQ and thus assumes the collection implements IEnumerable<string> and that you have a using declaration for System.LINQ

    You can wrap that up in a function as follows

    string GetUniqueString(IEnumerable<string> Collection, bool OrderMatters = true, string Escape = "/", string Separator = ":")
    {
        if(Escape == Separator)
            throw new Exception("Escape character should never equal separator character because it fails in the case of empty strings");
        if(!OrderMatters) 
            Collection = Collection.OrderBy(v=>v);//Sorting fixes ordering issues.
        return Collection
            .Select(v=>v.Replace(Escape, Escape + Escape).Replace(Separator,Escape + Separator))//Escape String
            .Aggregate((a,b)=>a+Separator+b);
    }