c#


Select more than one property using Linq


Let's say we have a Line class defined by Point startPoint and Point endPoint.
If I have list of these lines, how can I extract all the points in them into one List<Point> using LINQ.
This is what I have so far:
IList<Point> points1 = lines.Select(o => o.StartPoint).ToList();
IList<Point> points2 = lines.Select(o => o.EndPoint).ToList();
IList<Point> points = points1.Concat(points2).ToList();
If you want a shorter way, you can do something like this:
var points = lines.SelectMany(l => new[] { l.StartPoint, l.EndPoint }).ToList();
However, your current code is debateably more readable, but more importantly, does not create an array for each line you iterate.
However, you don't need to invoke ToList() for each set, you can simply write:
var points = lines.Select(l => l.StartPoint).Concat(lines.Select(l => l.EndPoint)).ToList();
You can do this in a few different ways. One is to use Tuple<Point, Point> :
IEnumerable<Tuple<Point, Point>> r = lines.Select(l => new Tuple<Point, Point>(l.StartPoint, l.EndPoint));
To access these then you have to keep in mind that StartPoint would be Item1 and EndPoint will be Item2 :
foreach ( Tuple<Point, Point> se in r )
{
var start = se.Item1;
var end = se.Item2;
}
Another one could be to make an array of 2 elements each :
IEnumerable<Point[]> r = lines.Select(l => new Point[2]{ l.StartPoint, l.EndPoint });
To access these you have to keep in mind that index 0 contains your StartPoint and index 1 contains your EndPoint :
foreach( Point[] parr in r )
{
if( parr.Length == 2 )
{
var start = parr[0];
var end = parr[1];
}
}
You can always create a flat model containing only these two properties and then just cast/create it in the Select.
There are dozens of ways to achieve what you want. The real question is what do you want to do with this result later.
Your solution is the closer you can get to it. If you don't want to enumerate twice the list you should go for a Foreach/Map approach:
var points = new List<Point>();
lines.Map(line =>
{
points.Add(line.startPoint);
points.Add(line.EndPoint);
} );
If you don't want to use Concat you can use Union:
lines.Select(o => o.StartPoint).Union(lines.Select(o => o.EndPoint)).ToList();

Related Links

COM Object Arrays From VB
“An item with same key has already been added” not getting this exception if adding duplicate object as a key in dictionary?
Cannot resolve binding in datatrigger wpf
unable to cast of type 'System.Data.EnumerableRowCollection`1[System.String]' to type 'System.IConvertible'
Xamarin.Forms: How To Avoid Hard-Coding a String in MVVM Bindings
Host MVC app on Azure Service Fabric
EF Core with Postgres is generating negative primary keys
Ignore missing fields in while Deserialisation using newtonsoft
How to add multiple records(rows) in 1 computer ID of DataGridView C#
Update excel file in VSTO project
CreateDelegate and AddEventHandler to a generic object with unknown arguments
logging to pappertrailapp using NLog in asp.net core (1.0.1)
Entity Framework Core 1.1.0 Data type conversion
Interface ICollection and AddRange C#/.NET
C# XML Data Deserialization - Apply object relationship based on reference ID
Posting to asp.net core mvc app results in null body and null input parameter

Categories

HOME
algolia
ide
compression
gaussian
arcgis
watson-iot
artifactory
ebay
css-selectors
aggregation-framework
richtextbox
atlassian-fisheye
servicenow
kohana
markdown
restheart
cracking
digital
popup
web-worker
ibatis
jquery-easyui
google-street-view
accordion
glibc
matlab-gui
infinite-loop
connection-pooling
waterfall
ballerinalang
spock
opencsv
log4net-configuration
odp.net
multi-user
kepserverex
anypoint-studio
instances
scalamock
jslider
observer-pattern
gridgain
spring-data-commons
hdpi
dcom
perldoc
android-vectordrawable
aot
printer-control-language
tsc
therubyracer
sqlproj
blitz3d
alarmmanager
instaparse
avi
avaudiorecorder
database-administration
ideavim
abstract
ios8-share-extension
recode
mojolicious
php-gd
uinavigationitem
dcg
tokudb
targetprocess
jeet-grid
gmaps4jsf
strcpy
sony-xperia
teamstudio-unplugged
iphone-6
random-access
diffmerge
pnunit
disparity-mapping
amzi-prolog
satisfiability
jsmpp
class-library
xcode6.1-gm-seed
maven-javadoc-plugin
xcode5.1
xrandr
leap-year
junction-table
phone-state-listener
gpl
qt5.1
ncml
jquery-1.8
shapado
beep
dancer
facebook-winjs-sdk
cherokee
openwrap
windows-xp-embedded
hs-err
cpack
cinder
newspeak
dojox.gfx
qlibrary
content-delivery-network
httpbrowsercapabilities
memory-consumption

Resources

Encrypt Message