Home > database >  Substring in Where Clause using Linq
Substring in Where Clause using Linq

Time:11-19

I am trying to get the files uploaded based on a Store Id that is being pulled off a table using Linq. Here's how I am getting the files:

var uploadedFiles = Files.OrderByDescending(x => x.LastWriteTime)
                                                .Select(x => new
                                                {
                                                    Name = x.Name,
                                                    Date = Convert.ToDateTime(x.LastWriteTime).ToString("MM/dd/yyyy")
                                                })
                                                .Where(x => x.Name
                                                .Contains(StoreId.ToString()))
                                                .ToList();

The format of the file "Name" is "123456789012_12345", where StoreId is everything after the underscore("_"). This condition brings the files based on the StoreId. However, it also brings more files than it is supposed to, because it looks for anything matching on the left hand side of the file name as well. If I change the condition to "Substring" I get no results back.

.Where(x => x.Name.Substring(0,13)
.Contains(StoreId.ToString()))
.ToList();

Is there anything I can do to get just the results that I am expecting?

Thank you!

CodePudding user response:

That is because Substring method returns you the left part of the name.

var str = "123456789012_12345";
var str2 = str.Substring(0, 13);
Console.WriteLine(str2); // 123456789012_

You could try:

var str2 = str.Substring(13, str.Length - 13);

or

var str2 = str.Split('_')[1];

or

.Where(x => x.Name.EndsWith($"_{StoreId}"));

CodePudding user response:

I would use this, since 13 is not reliable number, it can be changed

var storeId = StoreId.ToString();

....
.Where(x => x.Name.Substring(x.Name.IndexOf("_") 1) == storeId)
.ToList();
  • Related