I have some text that contains numerous values like so:
PartNumber Description Amount
Fid1 blahblahblah 999934109
0603 moreblah 12
exclude ehh? 981
FID5 fillertext 123
fid2 fillertext 123
fid fillertext 123
0603 fillertext 123
0603 fillertext 123
0603 fillertext 123
0402 fillertext 123
0402 fillertext 123
//etc.........etc............etc
I would like to print out the values that contain "FID"
int j = 1;
foreach (var line in theList)
{
if (line.PartNumber.ToUppeR().Contains("FID"))
{
sw.WriteLine("{0}: {1} {2} {3}",
j,
line.PartNumber,
line.Amount,
line.Description);
j++;
}
}
However, when I do this, it prints them out as follows:
1: Fid1 999934109 blahblahblah
2: FID5 123 开发者_运维技巧fillertext
3: fid2 123 fillertext
4: fid 123 fillertext
and I would like to print them out numerically.. so like this:
1: fid 123 fillertext
2: Fid1 999934109 blahblahblah
3: fid2 123 fillertext
4: FID5 123 fillertext
Is there an easy, quicky way to do this?
You could probably use the orderby clause of a LINQ query against theList:
int garbage;
from line in theList
where line.PartNumber.ToUpper().StartsWith("FID")
orderby (Int32.TryParse(line.PartNumber.Substring(3),garbage)) ? (Int32.Parse(line.PartNumber.Substring(3))) : 0
select line;
You wouldn't need the if statement in your foreach, then, either.
Fixed Jim's answer so it works: see also http://ideone.com/LIawL
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestThat
{
class MainClass
{
public static void Main (string[] args)
{
var theList = new [] {
new { PartNumber="FID34" }
};
var result = theList
.Where (line => line.PartNumber.StartsWith("FID", StringComparison.CurrentCultureIgnoreCase)
.OrderBy (line =>
{
int pnumber;
return Int32.TryParse(line.PartNumber.Substring(3), out pnumber)
? pnumber
: 0;
});
}
}
}
The lines could be stored in a sorted list. The key could be the number, for non existing numbers, you could use a zero, or the key could be the entire "FID".
I am not sure if FIDs repeat, which would make this approach not doable. Also, if the file is huge, may not be doable as well.
http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx
精彩评论