Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to exclude fields starting with numbers in LINQ

What I have tried:

I know we can do it in Sql as

select * from UserTable where username not  LIKE '%[0-9]%'


How to do the same in LINQ
Posted
Updated 20-Jun-19 22:49pm
Comments
BillWoodruff 21-Jun-19 4:19am    
Are the Fields starting with numbers actual numeric values, or are they strings ? Do you perhaps mean exclude "Rows" ?

Assuming:

1. 'UserTable is a DataTable

2. you have added a reference to System.Data.DataSetExtensions.dll : so you can use the 'Field extension method [^]

3. the 'UserName Column is of type 'string:
IEnumerable<DataRow> data = UserTable.Rows.Cast<DataRow>()
    .Where((DataRow row) =>
        ! char.IsDigit(row.Field<string>("UserName")[0]));
 
Share this answer
 
v2
Comments
Maciej Los 21-Jun-19 5:07am    
5ed!
Like operator is translated to:
C#
var data = context.UserTable.Where(x=>x.username.Contains("whatever"));

for excluding:
C#
var data = context.UserTable.Where(x=>!x.username.Contains("whatever"));

But, seems you want to use Regex, so follow this: How to: Combine LINQ Queries with Regular Expressions (C#) | Microsoft Docs[^]

Example:
C#
List<string> users = new List<string>(){"Adam", "0Barbara", "Aegon", "1Cecylia",
				"Zea", "999Robert", "H8tor", "Gre0on",};

string pattern = @"^\d.*$";
Regex r = new Regex(pattern);

var data = users.Where(u=>!r.IsMatch(u));
foreach(string s in data)
	Console.WriteLine($"{s}");


EDIT #1
You might be interested in usage of below methods too:
String.StartsWith Method (System) | Microsoft Docs[^]
String.EndsWith Method (System) | Microsoft Docs[^]
 
Share this answer
 
v4
Comments
BillWoodruff 21-Jun-19 4:50am    
You can't use Linq directly on either DataTable or DataTable.Rows
Maciej Los 21-Jun-19 4:57am    
I do not see such of requirement, Bill.
BTW: this is very good note.
BillWoodruff 21-Jun-19 5:05am    
the nature of a DataTable RowCollection demands the kind of casting I show in my response :)

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