1

I have an ICollectionView built from a LINQ to Entities query comprised of an anonymous object ...I want to apply filter to this collection, however the Filter property expects a Predicate

What can I do in order to apply the filter on this anonymously typed collection?

var playerDatabase = (from p in NFLDataContext.DimPlayers
                    join c in NFLDataContext.DimColleges on p.CollegeID equals c.CollegeID
                    join pos in NFLDataContext.DimPositions on p.PositionID equals pos.PositionID
                    select new
                    {
                        FirstName = p.FirstName,
                        LastName = p.LastName,
                        FullName = p.FirstName + " " + p.LastName,
                        CollegeName = c.CollegeName,
                        CollegeID = p.CollegeID,
                        PositionCode = pos.PositionCode,
                        PositionName = pos.PositionName,
                        PositionID = p.PositionID,
                        PlayerID = p.PlayerID
                    }).ToList();


        dgPlayers.ItemsSource = playerDatabase;

Elsewhere in an event handler ....

        string SomeFilterCondition;
        ICollectionView view = CollectionViewSource.GetDefaultView(dgPlayers.ItemsSource);
        view.Filter = (item) =>
        {
             ?????????????
        };

How about casting it to dynamic? Smth like:

var dynamicItem = item as dynamic;
return dynamicItem.FirstName == "Heines";

Otherwise you could checkout this answer for casting to an anonymous type - however, as the poster mentions, this probably does not make much sense in most scenarios :-)

https://stackoverflow.com/a/1409776/454272

4

3 回答 3

3

将其转换为动态怎么样?喜欢:

var dynamicItem = item as dynamic;
return dynamicItem.FirstName == "Heines";

否则,您可以签出此答案以转换为匿名类型-但是,正如海报所提到的,这在大多数情况下可能没有多大意义:-)

https://stackoverflow.com/a/1409776/454272

于 2012-08-19T07:08:53.330 回答
2

This should work -

view.Filter = (item) =>
        {
             dynamic anyonymousItem = item;
             // Your condition here
             return anyonymousItem.CollegeID == 1;
        };
于 2012-08-19T08:02:18.370 回答
1

Using dynamc is not the best option here in my opinion. You should create a class which contains your propertys (e.g. Player) and then change your query to select new Player(). In the filter you can then check if the object is of type Player and cast if necessary.

Like this you don't have to rely on dynamic dispatch and get all of the benefits of static typing (e.g. compile time errors if you write the property name wrong or change its name).

于 2012-08-19T09:18:01.787 回答