PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 17, 2022

[FIXED] How do I find partial duplicate on first element of a delimited string?

 May 17, 2022     arrays, c#, duplicates, partial, split     No comments   

Issue

I have a pipe delimited text file that I read into a string array. The text file will have 2 elements, and the first element could possibly have one or more duplicates. If there are any duplicates, I want to concatenate the values into 1.

Example Text File:

ABC|111
DEF|222
GHI|333
ABC|444
JKL|555
ABC|666

In this example, "ABC" is duplicated 3 times. I would like to concatenate the values into a single line separated with a '~' sign.

New string array values:

ABC|111~444~666
DEF|222
GHI|333
JKL|555

The order of the list is not important. I know how to find duplicate values of an entire line using .Distinct(), but I am not sure how to do this with only the first element of the string array. I would provide some code of my attempt, but I honestly have no idea how to even begin to achieve the desired results. Any help is appreciated! Thanks.

(Apologies if this post is duplicated. I had to refresh the page.)

Edit The text file can contain anywhere from 10,000 - 100,000 values.


Solution

Here's a quick one that can perhaps get you started:

Dictionary<string,List<string>> unDupe = new Dictionary<string, List<string>>();

for (int i = 0; i < yourArray.Length; i++)
{
    string[] split = yourArray[i].Split('|');
    if (unDupe.ContainsKey(split[0]))
    {
        unDupe[split[0]].Add(split[1]);
    }
    else
    {
        unDupe.Add(split[0], new List<string>() { split[1] });
    }
}

List<string> undupinated = new List<string>();

foreach (var keyValuePair in unDupe)
{
    undupinated.Add(string.Concat(keyValuePair.Key, "|", string.Join("~", keyValuePair.Value)));
}


Answered By - SharpNip
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing