linq - Get index of first list and use it in another list -
i have 2 lists:
list1 has values like: "a, a, a, a, b, b, b, b, c, c, c, c, c... on list2 has values like: "0, 1, 2, 2, 1.1, 1.2, 1.3, 4, 4, 4, 4.... on i want index of list1 values of lets b , find corrosponding values in list2. doing getting start , end index of list1 value b. looping through list2 indexes , getting values. seems work , lot of overhead. there better way of doing using linq?
i used this: var list1values = list1.findall(x => x.contains("b")); gives me values b stuck after how can corresponding values list2 after this? findall dont give index. 1 thought loop through index of list1values , list2 values dont think right way it.
provided both lists have same length, use zip pair corresponding items both sequences:
var target = "b"; var result = list1.zip(list2, (x,y) => tuple.create(x,y)) .where(o => o.item1 == target); foreach(var item in result) { console.writeline(item.item2); } i used tuple, item1 letter list1 , item2 corresponding item in list2. of course could've used anonymous type , given more meaningful name instead.
update: noticed tagged question c#-3.0. in case, use solution below. zip , tuple introduced in .net 4.0. solution below uses select method, available in .net 3.5. both solutions use linq, need add namespace: using system.linq;
another solution use overloaded select method indices of target letter, grabbing items second list based on indices.
var target = "b"; var targetindices = list1.select((o, i) => new { value = o, index = }) .where(o => o.value == target); var query = targetindices.select(o => list2[o.index]); foreach(var item in query) { console.writeline(item); }
Comments
Post a Comment