Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Substring in Where Clause using Linq

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you!

>Solution :

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}"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading