如何从实际对象列表创建一个对象属性的列表? [英] How to create a list of one object attributes from the actual list of objects?

查看:73
本文介绍了如何从实际对象列表创建一个对象属性的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义了Connection的对象的ObservableCollection.

I have an ObservableCollection of object that I've define Connection.

如何从该列表中的所有连接中提取所有URL?

How can I extract all URL from all connections in that list?

我想以正确的方式做类似的事情:

I want to do something like that but in the correct way:

ObservableCollection<Connection> connectionList;
List<string> listUrl = new List<string>();

foreach (var connection in connectionList)
{
    listUrl.Add(connection.PortalUrl);
}

推荐答案

以正确的方式"

"in the correct way"

您的方法没有什么错误",但是如果您使用的是.NET 3.5或更高版本,则可以使用Linq在同一行中完成 :

Well there's nothing "wrong" with your approach, but if you're using .NET 3.5 or higher it could be done in one line using Linq:

List<string> listUrl = connectionList.Select(c => c.PortalUrl).ToList();

如果您不了解Linq的工作方式,请坚持使用您的方法-它们在功能上是等效的.

If you don't understand how Linq works then stick with your method - they're functionally equivalent.

如果您尚未在项目中使用过Linq,只需将using System.Linq;和其他名称空间导入一起添加到类文件的顶部

If you haven't used Linq in your project yet just add using System.Linq; to the top of the class file along with the other namespace imports

这篇关于如何从实际对象列表创建一个对象属性的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆