1

I have an AsyncObservable collection of some class, say "dashboard". Each item inside dashboard collection contains a collection of some other class, say "chart". That chart has various properties such as name,type etc... I want to search based on chart name, type etc on this collection. Can anybody suggest me some searching technique? Currently I am searching by traversing the whole collection using a foreach and comparing entered input with each item inside the collection (this is not so efficient if amount of data is large)... I want to make it more efficient - I am using c#..

My code is:

foreach (DashBoard item in this.DashBoards)   
  {  
   Chart obj1 = item.CurrentCharts.ToList().Find(chart =>     chart.ChartName.ToUpper().Contains(searchText.ToUpper()));   
                    if (obj1 != null)  
                    {  
                        if (obj1.IsHighlighted != Colors.Wheat)  
                            obj1.IsHighlighted = Colors.Wheat;      
                        item.IsExpanded = true;   
                        flagList.Add(1);   
                    }  
                    else   
                    {    
                        flagList.Add(0);  
                }    
    }
Matt Tester
  • 4,663
  • 4
  • 29
  • 32
swapnil
  • 1,092
  • 7
  • 16

1 Answers1

2

You can use the LINQ query.

For example something you can do like this.If you post your code,we can solve the problem

Dashboard.SelectMany(q => q.Chart).Where(a => a.Name == "SomeName")

Here is the reference linq question: querying nested collections

Edit:Foreach loops or LINQ

The answer is not really clear-cut.There are two sides to any code cost arguments: performance and maintainability.The first of these is obvious and quantifiable.

Under the hood LINQ will iterate over the collection, just as foreach will. The difference between LINQ and foreach is that LINQ will defer execution until the iteration begins.

Performance wise take a look at this blog post: http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html

In your case:

If the collection is relatively small or medium size i would suggest you to use foreach for better performance.

At the end of the day. Linq is more elegant but less efficient most of the time, foreach clutters the code a bit but perform better.

On large collections/on a where using parallel computing make sense i would choose LINQ as the performance gaps will be reduced to minimum.

Community
  • 1
  • 1