c# linq conditional union
hi I have the following code and would like to only make each union if a condition is true. I Know I could write a select of if else but wanted to know if there is a slicker Linq way!?
//join the开发者_如何学编程 list into one and sort by seqnumber
SegmentList = Alist.Cast<BaseSegment>()
.Union(BList.Cast<BaseSegment>()).Union(CList.Cast<BaseSegment>())
.OrderBy(item => item.SegSeqNumber).ToList();
So given the above if ATest =true how do I only iclude Alist like wise if BTest && CTest are true how do I include only BList and Clist
Thanks
To do it in a LINQ style way with your checkboxes, something like:
SegmentList = Alist.Where(i => checkbox1.IsChecked).Cast<BaseSegment>()
.Union(BList.Where(i => checkbox2.IsChecked).Cast<BaseSegment>())
.Union(CList.Where(i => checkbox3.IsChecked).Cast<BaseSegment>())
.OrderBy(item => item.SegSeqNumber).ToList();
would work. But I don't think it is either very understandable or efficient.
Something like this?
SegmentList = Alist.Cast<BaseSegment>()
.Union(includeB ? BList.Cast<BaseSegment>() : Enumerable.Empty<BaseSegment>())
.Union(includeC ? CList.Cast<BaseSegment>() : Enumerable.Empty<BaseSegment>())
.OrderBy(item => item.SegSeqNumber)
.ToList();
This is not identical to your original (it will remove duplicates from Alist no matter what) but should be what you want.
For any more than 2 conditional unions, you would probably want a different query, something like:
var listsByCb = new Dictionary<CheckBox, MyListType>
{{ aListBox, aList}, {bListBox, bList}, {cListBox, cList}};
var segmentList = listsByCb.Where(kvp => kvp.Key.Checked)
.SelectMany(kvp => kvp.Value.Cast<BaseSegment>())
.Distinct();
.OrderBy(item => item.SegSeqNumber)
.ToList();
try something like
SegmentList = Alist.Cast<BaseSegment>().Where(z=>ATest)
.Union(BList.Cast<BaseSegment>().Where(x=>Btest)).Union(CList.Cast<BaseSegment>().Where(c=>Ctest))
.OrderBy(item => item.SegSeqNumber).ToList();
where class in each case will return all elements if corresponding test is true and will return no element otherwise. its completely untested though
Use a Where()
clause for that, like following:
//join the list into one and sort by seqnumber
SegmentList =
Alist.Cast<BaseSegment>().Where(a => ATest(a))
.Union(
BList.Cast<BaseSegment>(.Where(b => BTest(b))
.Union(CList.Cast<BaseSegment>().Where(c => CTest(c))
.OrderBy(item => item.SegSeqNumber).ToList();
By the way, do you really need the last ToList()
?
精彩评论