c# - How to create a List<int> basead on two properties from another list? -
problem
i need create list<int>
basead on 2 properties list.
example
i have class has 2 fields need.
public class myclass { //other fields int? valueid int? valuetwoid }
above code it's example, not focus there.
i want retrieve properties like:
myclasslist.elementat(0).valueid = 1; myclasslist.elementat(0).valuetwoid = 2; myclasslist.elementat(1).valueid = 3; myclasslist.elementat(1).valuetwoid = 4; list<int> resultlist = myclasslist.where(x => x.valueid != null && x.valuetwoid != null).select(x => ??).tolist());
desired output
resultlist.elementat(0) == 1 resultlist.elementat(1) == 2 resultlist.elementat(2) == 3 resultlist.elementat(3) == 4
there's way achieve using .select(x => ).tolist()
, without using code like:
list<int> resultlist = new list<int>(); foreach(var item in myclasslist) { resultlist.add(item.valueid); resultlist.add(item.valuetwoid); }
thanks in advance, sorry poor english.
try
list<int> resultlist = myclasslist .where(x => x.valueid != null && x.valuetwoid != null) .selectmany(x => new list<int>{x.valueid.value, x.valuetwoid.value}) .tolist();
as in:
using system; using system.collections.generic; using system.linq; namespace example { internal class program { public static void main(string[] args) { var myclasslist = new list<myclass> {new myclass(), new myclass()}; myclasslist.elementat(0).valueid = 1; myclasslist.elementat(0).valuetwoid = 2; myclasslist.elementat(1).valueid = 3; myclasslist.elementat(1).valuetwoid = 4; var resultlist = myclasslist .where(x => x.valueid != null && x.valuetwoid != null) .selectmany(x => new list<int> { x.valueid.value, x.valuetwoid.value}) .tolist(); foreach (var in resultlist) { console.writeline(i); } //prints out: //1 //2 //3 //4 console.readline(); } public class myclass { public int? valueid; public int? valuetwoid; } } }
Comments
Post a Comment