Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq select strings from list when condition is met and save the index

I have a list of strings

List<string> lstOne = new List<string>() { "January:1", "February", "March:4"};

And I am filtering the strings that contain : with this code

var withcolumns = lstOne.Find(t => t.Contains(':'));

and I am getting a new list with { "January:1", "March:4"}

I want to select in a new list the values January:1 and March:4 but also save the indexes of then in the previous list so the result would be

"0" "January:1"
"2" "March:4"

I can be simple or complicated but right now my brain is not functioning to solve this issue.

like image 983
ademg Avatar asked Nov 21 '25 10:11

ademg


2 Answers

list.Select((item, index) => new { item, index })
    .Where(o => o.item.Contains(':'))
like image 60
SLaks Avatar answered Nov 24 '25 01:11

SLaks


not sure what you want as the result ? a list of strings? or ?

but anyways.....with the index prefixed to your string...

List<string> lstOne = new List<string>() { "January:1", "February", "March:4" };
var list = lstOne.Select((s, i) => i+ " " + s ).Where(s => s.Contains(":")).ToList();
like image 44
Keith Nicholas Avatar answered Nov 24 '25 00:11

Keith Nicholas