我有可观察的类型收集,并且在很多地方需要删除一些具有条件的元素,例如" number == 2"。但是当它崩溃时它有很多弱点。如何改进代码?写一些扩展方法来检查条件" if(temp!= null)",或?
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication5
{
public class DataStruct
{
public int number { get; set; }
}
class Program
{
static void Main(string[] args)
{
ObservableCollection<DataStruct> Test = new ObservableCollection<DataStruct>();
for (int i=0;i<5;i++)
{
Test.Add(new DataStruct { number=i});
}
DataStruct temp = Test.Where(k => k.number ==2).FirstOrDefault();
if (temp != null)
{
int index = Test.IndexOf(Test.Where(k => k.number == 2).FirstOrDefault());
try
{
Test.Remove(Test[index]);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
foreach (DataStruct item in Test)
{
Console.WriteLine(item.number);
}
}
}
}
答案 0 :(得分:0)
您可以创建扩展方法来完成所有操作。例如:
<?php echo wpautop(get_the_content());?>
像这样使用:
static class Extensions
{
public static DataStruct Filter(this IEnumerable<DataStruct> collection) {
if (collection == null) {
return null; // or throw if you like
}
return collection
.Where(k => k.number ==2)
.FirstOrDefault();
}
}
但您也可以创建Test.Filter()
:
EmptyIfNull
并像这样使用它:
static class Extensions
{
public static DataStruct EmptyIfNull(this IEnumerable<DataStruct> collection) {
if (collection == null) {
return return new DataStruct[0];
}
return collection;
}
}