开发者

Better way of searching through lists than using foreach

list vclAsset<FullAsset>
list callsigns<string>

foreach(FullAsset fa in vclAsset)
{
    if (callsigns.contains(fa.asset.callsign))
    {
         //do something
    }

}

Is there a more elegant way to do the above? A FullAsset object contains an Asset object which in turn has a string "Callsign."开发者_开发百科 Each callsign will be unique, so my list callsigns will only have one of each string, and no two FullAsset objects will share an Asset.callsign variable.

In a nutshell I want to pull all the FullAssets that have a certain callsign, but using a foreach seems clumsy (given that the number of FullAssets that could be contained in said list potentially has no upper limit).


You could use a lambda expression, something like this:

foreach(FullAsset fa in vclAsset.Where(a => callsigns.contains(a.asset.callsign))
{
    // do something
}


If your keys are unique, you can use a Dictionary or a Hashtable to speed up searching.

If you only want to find a certain item, you can use the List<T>.Find method and supply a predicate.

FullAsset result = vclAsset.Find
     (fa => callsigns.contains(fa.asset.callsign));

or

List<FullAsset> results = vclAsset.FindAll
     (fa => callsigns.contains(fa.asset.callsign));

If you are using .Net 3.5, LINQ Where may be a better solution, as others have stated, since it returns an enumerator (lazy evaluation) vs a full List.


Sure, using linq.

var assets=    vclAsset.Where(fullA=>allsigns.contains(fullA.asset.callsign));

assets will be some enumerable structure.

I can recommend 100 Linq samples for inspiration and learning


Not sure if it counts as more elegant but you can use linq...

        var results = from fa in vclAsset
                      where callsigns.Contains(fa.asset.callsign)
                      select fa;


var result = vclAsset.Where(x=>callsigns.Any(y=>x.asset.callsign==y));

P.s. I would rename vclAsset and asset/callsign properties.


You can also use the Join function to do this.

var sortedList = vclAsset.Join(callsigns,
    x => x.asset.callsign, x => x,
    x, y => x);

This is the list of vclAssets that have the listed callsign.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜