Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将列表复制到另一个列表,但不包括列表类型的某些属性_C#_List_Dynamic_Anonymous Types - Fatal编程技术网

C# 将列表复制到另一个列表,但不包括列表类型的某些属性

C# 将列表复制到另一个列表,但不包括列表类型的某些属性,c#,list,dynamic,anonymous-types,C#,List,Dynamic,Anonymous Types,这看起来应该很容易,但我想不出一个整洁的方法来做 和全班同学一起 class SomeType { public int SomeInteger {get;} public string SomeString {get;} public object SomeObject {get;} } 假设某个类型的列表是从某处检索到的,但是我需要从列表中的每个项目中删除SomeString字段。因此,我迭代列表,创建一个匿名类型并将其添加到新列表中 List<SomeType&

这看起来应该很容易,但我想不出一个整洁的方法来做

和全班同学一起

class SomeType
{ 
   public int SomeInteger {get;}
   public string SomeString {get;}
   public object SomeObject {get;}
}
假设某个类型的列表是从某处检索到的,但是我需要从列表中的每个项目中删除SomeString字段。因此,我迭代列表,创建一个匿名类型并将其添加到新列表中

List<SomeType> list = GetList();

var newList = new List<dynamic>();
list.ForEach(item => newList.Add(new { SomeInteger = item.SomeInteger, SomeObject = item.SomeObject });
List List=GetList();
var newList=新列表();
ForEach(item=>newList.Add(new{SomeInteger=item.SomeInteger,SomeObject=item.SomeObject});

有没有更好的方法不需要我创建一个空的动态类型列表?我可能错了,但感觉这不是最好的方法。

您可以直接创建一个匿名类型列表,这将是强类型的:

list.Select(item => new 
                    { 
                        SomeInteger = item.SomeInteger, 
                        SomeObject = item.SomeObject
                    }).ToList();

声明
newList
不需要额外的语句。c编译器可以自动确定类型。有关详细信息,请参阅

 var newList = GetList()
  .Select(x => new { SomeInteger = x.SomeInteger, SomeObject = x.SomeObject})
  .ToList();

可能是重复的感谢,我知道必须有一个更好的方式!