使用 lambda 表达式将对象列表从一种类型转换为另一种类型

发布于 2024-08-15 07:56:11 字数 301 浏览 3 评论 0 原文

我有一个 foreach 循环读取一种类型的对象列表并生成不同类型的对象列表。有人告诉我 lambda 表达式可以达到相同的结果。

var origList = List<OrigType>(); // assume populated
var targetList = List<TargetType>(); 

foreach(OrigType a in origList) {
    targetList.Add(new TargetType() {SomeValue = a.SomeValue});
}

I have a foreach loop reading a list of objects of one type and producing a list of objects of a different type. I was told that a lambda expression can achieve the same result.

var origList = List<OrigType>(); // assume populated
var targetList = List<TargetType>(); 

foreach(OrigType a in origList) {
    targetList.Add(new TargetType() {SomeValue = a.SomeValue});
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

三人与歌 2024-08-22 07:56:11

尝试以下方法

var targetList = origList
  .Select(x => new TargetType() { SomeValue = x.SomeValue })
  .ToList();

这是使用 Lambda 和 LINQ 的组合来实现解决方案。 Select 函数是一种投影样式方法,它将把传入的委托(或本例中的 lambda)应用于原始集合中的每个值。结果将在新的 IEnumerable 中返回。 .ToList 调用是一种扩展方法,它将将此 IEnumerable 转换为 List

Try the following

var targetList = origList
  .Select(x => new TargetType() { SomeValue = x.SomeValue })
  .ToList();

This is using a combination of Lambdas and LINQ to achieve the solution. The Select function is a projection style method which will apply the passed in delegate (or lambda in this case) to every value in the original collection. The result will be returned in a new IEnumerable<TargetType>. The .ToList call is an extension method which will convert this IEnumerable<TargetType> into a List<TargetType>.

披肩女神 2024-08-22 07:56:11

如果您知道想要从List转换为List,那么List.ConvertAll 将比 Select/ToList 因为它知道开始时的确切大小:

target = orig.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });

在更一般的情况下,当您只知道源为 IEnumerable 时,使用 选择/ToList 是正确的选择。您可能还认为,在使用 LINQ 的世界中,从这里开始更为惯用……但至少值得了解 ConvertAll 选项。

If you know you want to convert from List<T1> to List<T2> then List<T>.ConvertAll will be slightly more efficient than Select/ToList because it knows the exact size to start with:

target = orig.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });

In the more general case when you only know about the source as an IEnumerable<T>, using Select/ToList is the way to go. You could also argue that in a world with LINQ, it's more idiomatic to start with... but it's worth at least being aware of the ConvertAll option.

慕巷 2024-08-22 07:56:11
var target = origList.ConvertAll(x => (TargetType)x);
var target = origList.ConvertAll(x => (TargetType)x);
找个人就嫁了吧 2024-08-22 07:56:11
List<target> targetList = new List<target>(originalList.Cast<target>());
List<target> targetList = new List<target>(originalList.Cast<target>());
呆橘 2024-08-22 07:56:11

我相信这样的事情应该有效:

origList.Select(a => new TargetType() { SomeValue = a.SomeValue});

I believe something like this should work:

origList.Select(a => new TargetType() { SomeValue = a.SomeValue});
小伙你站住 2024-08-22 07:56:11

这是一个简单的例子..

List<char> c = new List<char>() { 'A', 'B', 'C' };

List<string> s = c.Select(x => x.ToString()).ToList();

Here's a simple example..

List<char> c = new List<char>() { 'A', 'B', 'C' };

List<string> s = c.Select(x => x.ToString()).ToList();
雨后咖啡店 2024-08-22 07:56:11
var list1 = new List<Type1>();
var list2 = new List<Type2>();

list1.ForEach(item => list2.Add(new Type2() { Prop1 = value1 }));
var list1 = new List<Type1>();
var list2 = new List<Type2>();

list1.ForEach(item => list2.Add(new Type2() { Prop1 = value1 }));
筑梦 2024-08-22 07:56:11

假设您有多个要转换的属性。

public class OrigType{
    public string Prop1A {get;set;}
    public string Prop1B {get;set;}
}

public class TargetType{
    public string Prop2A {get;set;}
    public string Prop2B {get;set;}
}

var list1 = new List<OrigType>();
var list2 = new List<TargetType>();

list1.ConvertAll(x => new OrigType { Prop2A = x.Prop1A, Prop2B = x.Prop1B })

Assume that you have multiple properties you want to convert.

public class OrigType{
    public string Prop1A {get;set;}
    public string Prop1B {get;set;}
}

public class TargetType{
    public string Prop2A {get;set;}
    public string Prop2B {get;set;}
}

var list1 = new List<OrigType>();
var list2 = new List<TargetType>();

list1.ConvertAll(x => new OrigType { Prop2A = x.Prop1A, Prop2B = x.Prop1B })
格子衫的從容 2024-08-22 07:56:11

或者使用构造函数 & linqSelect

public class TargetType {
  public string Prop1 {get;set;}
  public string Prop1 {get;set;}

  // Constructor
  public TargetType(OrigType origType) {
    Prop1 = origType.Prop1;
    Prop2 = origType.Prop2;
  }
}

var origList = new List<OrigType>();
var targetList = origList.Select(s=> new TargetType(s)).ToList();  

Linq 线条更加柔和! ;-)

Or with a constructor & linq with Select:

public class TargetType {
  public string Prop1 {get;set;}
  public string Prop1 {get;set;}

  // Constructor
  public TargetType(OrigType origType) {
    Prop1 = origType.Prop1;
    Prop2 = origType.Prop2;
  }
}

var origList = new List<OrigType>();
var targetList = origList.Select(s=> new TargetType(s)).ToList();  

The Linq line is more soft! ;-)

自我难过 2024-08-22 07:56:11

如果需要使用函数来强制转换:

var list1 = new List<Type1>();
var list2 = new List<Type2>();

list2 = list1.ConvertAll(x => myConvertFuntion(x));

我的自定义函数在哪里:

private Type2 myConvertFunction(Type1 obj){
   //do something to cast Type1 into Type2
   return new Type2();
}

If you need to use a function to cast:

var list1 = new List<Type1>();
var list2 = new List<Type2>();

list2 = list1.ConvertAll(x => myConvertFuntion(x));

Where my custom function is:

private Type2 myConvertFunction(Type1 obj){
   //do something to cast Type1 into Type2
   return new Type2();
}
羁客 2024-08-22 07:56:11

对于类似类型的类。

列表<目标列表> targetlst= JsonConvert.DeserializeObject>(JsonConvert.SerializeObject());

for similar type class.

List<targetlist> targetlst= JsonConvert.DeserializeObject<List<targetlist>>(JsonConvert.SerializeObject(<List<baselist>));

人间不值得 2024-08-22 07:56:11

如果类型可以直接转换,这是最干净的方法:

var target = yourList.ConvertAll(x => (TargetType)x);

如果类型不能直接转换,那么您可以将属性从原始类型映射到目标类型。

var target = yourList.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });

If the types can be directly cast this is the cleanest way to do it:

var target = yourList.ConvertAll(x => (TargetType)x);

If the types can't be directly cast then you can map the properties from the orginal type to the target type.

var target = yourList.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });
稀香 2024-08-22 07:56:11

如果从一个列表映射到另一个列表时需要进行转换,您可以从 Convertall 调用一个函数来测试转换。

public int StringToInt(String value)
        {
            try
            {
                return Int32.Parse(value);
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
        [Fact]
        public async Task TestConvertAll()
        { 
            List<String> lstString = new List<String>{"1","2","3","4","5","6","7","8","9","10" };

            List<int> lstInt = lstString.ConvertAll(new Converter<String, int>(StringToInt));
            foreach (var item in lstInt)
            {
                output.WriteLine("{0}", item);
            }
            if (lstInt.Count()>0) {
                Assert.True(true);
            }
        }

If casting when mapping from one list to another is required, from convertall, you can call a function to test the casting.

public int StringToInt(String value)
        {
            try
            {
                return Int32.Parse(value);
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
        [Fact]
        public async Task TestConvertAll()
        { 
            List<String> lstString = new List<String>{"1","2","3","4","5","6","7","8","9","10" };

            List<int> lstInt = lstString.ConvertAll(new Converter<String, int>(StringToInt));
            foreach (var item in lstInt)
            {
                output.WriteLine("{0}", item);
            }
            if (lstInt.Count()>0) {
                Assert.True(true);
            }
        }
初心未许 2024-08-22 07:56:11

我们首先考虑List类型是String,并且想将其转换为List的Integer类型。

List<String> origList = new ArrayList<>(); // assume populated

在原始列表中添加值。

origList.add("1");
origList.add("2");
    origList.add("3");
    origList.add("4");
    origList.add("8");

使用 forEach创建整数类型

List<Integer> targetLambdaList = new ArrayList<Integer>();
targetLambdaList=origList.stream().map(Integer::valueOf).collect(Collectors.toList());

打印列表值的目标列表:

    targetLambdaList.forEach(System.out::println);

We will consider first List type is String and want to convert it to Integer type of List.

List<String> origList = new ArrayList<>(); // assume populated

Add values in the original List.

origList.add("1");
origList.add("2");
    origList.add("3");
    origList.add("4");
    origList.add("8");

Create target List of Integer Type

List<Integer> targetLambdaList = new ArrayList<Integer>();
targetLambdaList=origList.stream().map(Integer::valueOf).collect(Collectors.toList());

Print List values using forEach:

    targetLambdaList.forEach(System.out::println);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文