Click here to Skip to main content
15,890,043 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello all,

I am trying to filter rows in a datatable by the given criteria:

(1)The rows should be seen in datatable if the column has a value other than white.
(2)The former and latter 2 rows must be added as well if the rule 1 is met.

For ex;

Input
LineNumber Desc Color
0001--------aas---White
0002-------brrf---White
0003--------vea---White
0004------adwec---White
0005------45fca---Green
0006-----fvsdca---White
0007-----rtvsca---White
0008-----4dsdea---White

Output
LineNumber Desc Color
0003--------vea---White
0004------adwec---White
0005------45fca---Green
0006-----fvsdca---White
0007-----rtvsca---White

What I have tried so far?
C#
var result = from r in dtOld.AsEnumerable()
             where r.Field<string>("Color") != "White"
             select r.Field<string>("Line#");

List<int> lstIntOld = new List<int>();
foreach (var item in result)
{
    int numberAdd = Convert.ToInt32(item.ToString().TrimStart('0'));
    lstIntOld.Add(numberAdd - 2);
    lstIntOld.Add(numberAdd - 1);
    lstIntOld.Add(numberAdd);
    lstIntOld.Add(numberAdd + 1);
    lstIntOld.Add(numberAdd + 2);
}

lstIntOld = lstIntOld.Distinct().Where(ix => ix >= 0).ToList();


I found the line numbers which I should add and put them to a list. Now I will filter the datatable by matching those numbers from that list. But is there a cleaner or better way to accomplish this?

Thanks in advance
Posted

1 solution

My compliment for your presentation of your question!

This is how I would do it - or at least my first second iteration *. Note there's no "dtNew" - I just remove the unwanted rows from "dtOld". If you want to keep "dtOld" around you would have to copy the rows.

C#
int inclusionSpan = 2;
bool[] keepRow = new bool[dtOld.Rows.Count + inclusionSpan * 2];
int colorColumnIndex = dtOld.Columns.IndexOf("Color");

for (int rowIndex = 0; rowIndex < dtOld.Rows.Count; rowIndex++)
{
    if (dtOld.Rows[rowIndex].Field<string>(colorColumnIndex) != "White")
    {
        for (int includeOffset = 0; includeOffset <= inclusionSpan * 2; includeOffset++)
            keepRow[rowIndex + includeOffset] = true;

        rowIndex += inclusionSpan;
    }
}

for (int rowIndex = dtOld.Rows.Count - 1; rowIndex >= 0 ; rowIndex--)
{
    if (! keepRow[rowIndex + inclusionSpan])
        dtOld.Rows.RemoveAt(rowIndex);
}

* : Tired, maybe there's a flaw somewhere with the inclusionSpan, would have to test it.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900