从通用列表中删除一个属性/列 [英] Remove a property/column from a generic list
问题描述
我有一个类:
$由于某些原因,我无法更改查询,因此我必须在C#中执行此操作。 b $ b
public class myClass
{
int id {get;组; }
字符串名称{get;组; }
DateTime sDate {get;组; }
bool status {get;组; }
}
我得到的数据在此列表中获取。现在我想要从具有 null
值的列表中删除这些属性。我听起来可能疯了,但你读得对。我想只用选定的属性创建另一个列表,但上述任何属性都可以是 null
。所以我必须设计一个机制来基于此过滤我的列表。
为了更加清晰,请考虑以下示例。
列表与LT; myClass的> lstClass =某些数据源。
获取数据后,通用列表(lstClass)看起来像这样。考虑表中的结果集:
Id名称Sdate状态
1 a null null
2 b null null
3 c null false
我可以在删除属性sdate后如何让我的列表看起来像这样。
因此,我想创建的新列表应该只有三个属性。
Id名称状态
1 a null
2 b null
3 c false
任何想法?我可以用Linq做这个吗?
PS:这与演示无关。我没有一个网格,我无法隐藏那些不是我正在寻找的列。
假设您有一个myClass实例的通用列表,您可以创建一个只包含所需属性的匿名类型:
List< myClass> list = ...;
var reducedList = list.Select(e => new {e.id,e.name,e.status})。ToList();
//注意:调用ToList()是可选的
foreach(reducedList中的var项)
Console.WriteLine(item.id ++ item.name ++ item.status);
//注意:项目没有属性sDate
}
Due to some reason I cannot change the query so I have to do this in C#.
I have a class:
public class myClass
{
int id { get; set; }
string name { get; set; }
DateTime sDate { get; set; }
bool status { get; set; }
}
The data I am getting is fetched in this list. Now what I want is to remove those properties from a list that has null
values. I may sound insane but you read it right. I thought of creating another list with only the selected properties, but any of the above properties can be null
. So I have to devise a mechanism to filter my list based on this.
For more clarity consider the following example.
List<myClass> lstClass = some data source.
After getting the data the generic list(lstClass) looks like this.Consider the result set in a table:
Id Name Sdate status
1 a null null
2 b null null
3 c null false
Can i some how make my list look like this after removing the property sdate. So the new list that I want to create should have only three properties.
Id Name status
1 a null
2 b null
3 c false
Any ideas? Can I do this using Linq?
PS: This has nothing to do with presentation. I don’t have a grid where I am not able to hide columns that Is not what I am looking for.
Assuming you have a generic list of myClass instances, you can create an anonymous type with only the needed properties:
List<myClass> list = ...;
var reducedList = list.Select(e => new {e.id, e.name, e.status}).ToList();
// note: call to ToList() is optional
foreach (var item in reducedList)
{
Console.WriteLine(item.id + " " + item.name + " " + item.status);
//note: item does not have a property "sDate"
}
这篇关于从通用列表中删除一个属性/列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!