c# - How to Select Items in an Observable Collection with a property that matches a criteria
问题描述
I have an Observable Collection of a Hymn Class and another Observable Collection of a HymntType Class as shown below
public class Hymn
{
public int Id { get; set; }
public int HymnNumber { get; set; }
public string Title { get; set; }
public string HymnTypeName { get; set; }
public string Body { get; set; }
}
public class HymnType
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
I have initialized these classes with members on their respective page view models and I would like to use the Title property of the HymnType to filter the Hymn observable collection for only Hymns that have HymnTypeName Property equal to the HymnType Title property when the user selects the user selects it.
I am using LINQ but I get null for the list of Hymns after the filter, here is an example of the code I used for the filter.
public class HymnTypeContentPageViewModel : BaseViewModel
{
ObservableCollection<Hymn> _hymns;
public ObservableCollection<Hymn> Hymns
{
get => _hymns;
set => SetProperty(ref _hymns, value);
}
public HymnTypeContentPageViewModel(HymnType hymnType)
{
string keyword = hymnType.Title.ToLower();
Hymns = new ObservableCollection<Hymn>
{
new Hymn
{
HymnNumber = 201,
Title = "All Things Bright and Beautiful",
HymnTypeName = StaticStrings.AncientAndModern,
Body = "Test Body Ancient and Modern"
},
new Hymn
{
HymnNumber = 270,
Title = "He Arose",
HymnTypeName = StaticStrings.SomeOtherHymns,
Body = "Test Body Some Other Hymn"
},
};
Hymns = Hymns.Where(h => h.HymnTypeName.ToLower().Contains(keyword)) as ObservableCollection<Hymn>;
}
}
Both the HymnType Class Title Property and the Hymn Class HymnTypeName property use the StaticString class for their values so it is very unlikely that it is a typo. I have tried using a foreach loop instead of LINQ and I still get null.
Not that if I do not apply the filter, I do not get null and the app works perfectly.
解决方案
You're getting NULL after casting IEnumerable<Hymn>
to ObservableCollection<Hymn>
.
Try replace it with:
Hymns = new ObservableCollection<Hymn>(Hymns.Where(h => h.HymnTypeName.ToLower().Contains(keyword)));
推荐阅读
- batch-file - 如何在 Windows 上为 .sh 文件编写等效的 xargs
- java - java中方法的未擦除抛出子句
- javascript - 我无法在 Google 协作平台上使用损坏的链接检查器检查损坏的链接
- python-3.x - python中子进程内部的多处理
- echarts - 如何从 apache eCharts 中的 zRender 点击事件中确定时间轴值
- ios - 关闭后对前一个视图控制器的操作
- powershell - Powershell:HRESULT 异常:0x80131047 与类创建
- flutter - Flutter - 用于空值 _CastError 的空检查运算符
- homebrew - 自制更改前缀
- python - python api sdk脚本从Thycotic文件夹中提取所有分泌物