c# - How to find the index of .First match? -
i'm using this:
foreach (var item in set) { string matchingstring = conlines.firstordefault(r => (r.indexof(item.firstparam) >= 0 && r.indexof(item.secondparam) >= 0) && (r.indexof(item.firstparam) < r.indexof(item.secondparam))); }
where:
list<string> conlines = ...
and
public class classname { public string firstparam { get; set; } public string secondparam { get; set; } } public static list<classname> set = ....
and want know @ index of conlines matchingstring found.
at end of day, i'm trying search through conlines, string string, matches firstparam , secondparam (sequentially, in same string of conlines). if match found, want change string in conlines. whether line finds match , gets changed or not, want print out. i'm reading in conlines , printing out including changes in lines found match firstparam , secondparam.
example:
if conlines were:
alpha beta dog cat chair ramp table seat blog journal article letter
and firstparam, secondparam included:
ramp, table article, letter
and changes made add -01 matches, printing out:
alpha beta dog cat char ramp-01 table-01 seat blog journal article-01 letter-01
no matter how find index, it's going sub-optimal. you'll wind enumerating collection twice. instead, should either:
use
for
loop loop on collection (if possible). way, whenever find fist match, you'll have index (only works if collection exposes , indexer , pre-calculated length/count property):for(var = 0; < collection.count; i++) { if(collection[i] == query) { // have match collection[i] , index in } }
loop on collection using
getenumerator
, count index using counter. workienumerable
:var enumerator = collection.getenumerator(); var count = 0; while(enumerator.movenext()) { if(enumerator.current == query) { // have match in enumerator.current , index in count } count++; }
either way, you'll have loop on collection single time rather twice (once firstordefault
, again index.
Comments
Post a Comment