How do we check contains if string with blank space in c#

Gani_tpt 1,506 Reputation points
2021-04-11T12:19:34.213+00:00

I am having the below data table values.

DataTable Dt = new DataTable();
Dt.Columns.Add("COL1", typeof(string));
Dt.Columns.Add("COL2", typeof(string));
Dt.Columns.Add("COL3", typeof(string));
Dt.Rows.Add("101", "XZ", "101XZ");
Dt.Rows.Add("101", "XY", "XY101");
Dt.Rows.Add("101", "ZZ", "101 ZZ");

I want to check, COL1 and COL2 values will be exists in COL3.

In the COL3 i have some spaces within the values. (101 ZZ).

so, the intention is, I want to check, COL1 and COL2 values will be exists in COL3.

How do we check..?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,036 Reputation points
    2021-04-11T15:15:21.583+00:00

    This will find any row where COL3 has a space and report the row index. This solution only satisfies what you wrote in the title.

    var results = Dt
        .AsEnumerable()
        .Select((row, index) => new {Row = row, Index = index})
        .Where(item => item.Row.Field<string>("COL3")
            .Contains(" "))
        .ToList();
    if (results.Count >0)
    {
        results.ForEach(x => Debug.WriteLine($"{x.Index}, '{x.Row.Field<string>("COL3")}'"));
    }
    

2 additional answers

Sort by: Most helpful
  1. Duane Arnold 3,211 Reputation points
    2021-04-11T14:12:46.837+00:00

    @Gani_tpt

    Basically, you detect if column3 data has a space in it with the string.contains().

    https://learn.microsoft.com/en-us/dotnet/api/system.string.contains?view=net-5.0

    You then use the string.Replace() to replace " " (the space) with "" a null string value.

    https://learn.microsoft.com/en-us/dotnet/standard/base-types/trimming#:~:text=You%20can%20also%20remove%20a,all%20commas%20from%20a%20string.

    if (column3.contains(" ") then
    {
    var stripspace = column3.replace(" ", "");

       // Then you do the compare using stripspace.  
    

    }
    It should work for you, hopefully. :)

    2 people found this answer helpful.

  2. Duane Arnold 3,211 Reputation points
    2021-04-12T18:14:33.903+00:00

    if (colum3.contains("AM") && column3.contains("120") then
    {
    // then it's true
    }

    1 person found this answer helpful.
    0 comments No comments