Search code examples
c#listlist-manipulation

Alter a list of strings based on the items


I have a problem with a list that I want to alter, before outputting it back to the client.

For the sake of the question I will post an example of the list and how I need to result to look, because I have looked at Intersect, Except and everything else I could think of, but didn't get the result I am looking for.

Example List:

1, 4, 6, 8
1, 2, 6, 8
2, 4, 6, 8
3, 4, 5, 7

Required Result:

1, 4, 6, 8 //Initial row
-, 2, -, - //Items that have not changed will show as a -
2, 4, -, -
3, -, 5, 7

I really hope I explained it well.

I would be happy to explain this further if needed.

Thanks in advance for the advice, so far I have wrecked my brain over this. ;)

What I tried is too much to type here, so here is what I have so far. Except simply won't do anything with the data because it thinks the rows are different, so they just stay the same.

private List<List<string>> FilterData(List<string[]> datatable)
    {
        List<string> previousRow = new List<string>();
        List<string> currentRow = new List<string>();
        List<string> rowDifferences = new List<string>();

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

        foreach (var item in datatable)
        {
            if (previousRow == null)
            {
                previousRow = item.ToList();
                continue;
            }

            currentRow = item.ToList();

            rowDifferences = currentRow.Except(previousRow).ToList();
            resultingDataset.Add(rowDifferences);
        }
        return resultingDataset;
    }

Solution

  • Few things you have to change in your code;

    Here is code:

     private List<string[]> FilterData(List<string[]> datatable)
        {
            // List is made of String Array, so need string[] variable not list
            string[] previousRow = null ;
            string[] currentRow;
            string[] rowDifferences ;
    
            // to store the result
            List<string[]> resultingDataset = new List<string[]>();
    
            foreach (var item in datatable)
            {
                if (previousRow == null)
                {
                    previousRow = item;
                    resultingDataset.Add(previousRow); // add first item to list
                    continue;
                }
    
                currentRow = item; 
    
                // check and replace with "-" if elment exist in previous 
                rowDifferences = currentRow.Select((x, i) => currentRow[i] == previousRow[i] ? "-" : currentRow[i]).ToArray();  
                resultingDataset.Add(rowDifferences);
    
                // make current as previos
                previousRow = item;
            }
            return resultingDataset;
        }
    

    check this dotnetfiddle