can Linq extract the largest numeric part from this string list?

R

Rich P

Here is the list and the Linq I am using to generate it:

ADT.JPG
ADT1.JPG
ADT10.GIF
ADT2.JPG
ADT3.JPG
ADT4.JPG
ADT5.BMP
ADT6.JPG
ADT7.BMP
ADT8.JPG
ADT8A.JPG
ADT9.GIF

var names =
from n in files
where n.Contains("ADT")
select Path.GetFileName(n);

foreach (string s in names)
Console.WriteLine(s);

the number I am looking for is "10" from

C:\1C\20CC\PICTURES\ADT10.GIF

I am looking for the largest numeric part of a filename. My actual list
will also contain strings like this:

ADT83A.JPG

where I would want to extract 83 from ADT83A.JPG. Can linq do this or
do I have to manually loop through this list?

In pseudocode I am thinking something like this:

-----------------------------------------------
char[] rgchDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
List<int> nums from n in names
where n.Contains(numeric chars
from rgchDigits)
select n;

var i = select max(int) from nums;
-----------------------------------------------

can I do something like this with linq? what would that look like?

No need to consider strings like "ADT8XX3.BMP. There is a convention
for this list where all numeric chars will be consecutive.

Thanks,

Rich
 
M

Martin Honnen

Rich said:
Here is the list and the Linq I am using to generate it:

ADT.JPG
ADT1.JPG
ADT10.GIF
ADT2.JPG
ADT3.JPG
ADT4.JPG
ADT5.BMP
ADT6.JPG
ADT7.BMP
ADT8.JPG
ADT8A.JPG
ADT9.GIF

var names =
from n in files
where n.Contains("ADT")
select Path.GetFileName(n);

foreach (string s in names)
Console.WriteLine(s);

the number I am looking for is "10" from

C:\1C\20CC\PICTURES\ADT10.GIF

I am looking for the largest numeric part of a filename.

This should do:

string[] names = {
"ADT.JPG",
"ADT1.JPG",
"ADT10.GIF",
"ADT2.JPG",
"ADT3.JPG",
"ADT4.JPG",
"ADT5.BMP",
"ADT6.JPG",
"ADT7.BMP",
"ADT8.JPG",
"ADT8A.JPG",
"ADT9.GIF"
};
int max = (from name in names
let n = Regex.Replace(name, "[^0-9]+", "")
where n != ""
select int.Parse(n)).Max();


Console.WriteLine(max);
 
R

Rich P

http://www.infoq.com/news/2007/09/LINQ-Aggregates
<<

Thanks for this link. And incase my last post didn't make it (we were
having internet connection problems at my place) I did try combining the
previous suggestion with my technique and it worked very nicely:

var names =
from n in files
where n.Contains("ADT")
select Path.GetFileName(n);

int max = (from name in names
let n = Regex.Replace(name, "[^0-9]+", "")
where n != ""
select int.Parse(n)).Max();

I am just going to have to keep doing what I am doing and learn linq the
hard way (so far - the hard way is the only way that seems to work for
me - consistently :)



Rich
 
Top