c#


Append single item to list in linq statement


Out of curiosity, I'd like to add an element to an enumerable from within a linq flow, without exiting the flow or casting the single element to an array.
So instead of this:
myEntity.SelectMany(e => e.SubEntities.Concat(new []{e})).yadayadayada
I want a different command where I wouldn't need to wrap the single element into an array:
myEntity.SelectMany(e => e.SubEntities.SomeBuiltInFunc(e)).yadayadayada
or
myEntity.SelectMany(e => e.SubEntities.ToList().SomeBuiltInFunc(e)).yadayadayada
or
myEntity.SelectMany(e => SomeBuiltInFunc(e.SubEntities, e).yadayadayada
Any construct in the language currently I'm missing that could do this, without creating a new custom function or extension method.
Interesting. First of all, you can't add elements to IEnumerable because not all IEnumerable are collections, for example. In order to achieve what you want, you'll need to eventually convert that IEnumerable into something like a List, for example.
I guess you're looking for extension methods, which is one possible solution I could figure out:
public class Entity
{
public IEnumerable<Entity> SubEntities { get; set; }
}
public static class EnumerableExtensions
{
public static IEnumerable<T> SomeBuiltInFunc<T>(this IEnumerable<T> enumerable, T item)
{
var list = enumerable.ToList();
list.Add(item);
return list;
}
}
...then you could call it like this:
IEnumerable<Entity> myEntities = new List<Entity>();
var entity = new Entity();
myEntities = myEntities.SelectMany(e => e.SubEntities.SomeBuiltInFunc(entity));
Take note I changed your myEntity to myEntities because SelectMany() is a built-in extension method from IEnumerable<T>. Also, if you need to pass an entire IEnumerable<T> as argument to your BuiltInFunc(), just change it to something like:
public static IEnumerable<T> SomeBuiltInFunc<T>(this IEnumerable<T> enumerable, IEnumerable<T> item)
{
var list = enumerable.ToList();
list.AddRange(item);
return list;
}
...then now:
IEnumerable<Entity> myEntities = new List<Entity>();
var entity = new Entity();
myEntities = myEntities.SelectMany(e => e.SubEntities.SomeBuiltInFunc(myEntities));
Finally, change the name of the SomeBuiltInFunc(), since it's not actually built-in.
I just want to make clear the problem with this solution is we might not preserve the original concrete type of the IEnumerable.
While the idea of working with interfaces is not caring at all about the implementation details (what is the concrete type), there might be situations where it does difference changing the concrete type. So you either find a way to solve this, or be careful whether this would be a problem for you or not.
recursive's answer was pretty good, I wonder how Enumerable.repeat(e, 1) compares to new [] {e}

Related Links

how do I copy a folder to a USB? C#
GDI+ and system graphics cards
How to expose IObservable<T> properties without using Subject<T> backing field
Assign tab content in WPF to a page
how to parse size of file to string
how do I shutdown my computer when multiple processes close?
Prevent console application from terminating
How to make a regex match case insensitive?
Positioning of controls is incorrect on another PC in a Windows Forms application [closed]
Deserializing xml element to Array with XmlSerializer doesn't work
Facebook photo competition app with c# [closed]
Silverlight images not displaying
How do I change and display a tooltip on a chart in c# when the mouse hovers over a bar?
Building an setup project, Error 1001 (Something wrong with the Custom Actions)
Which type in C# can render this json collection
How to detect loading of imge is completed in Awesomium.net?

Categories

HOME
google-cloud-pubsub
cors
fortran
customization
pelican
magento-1.9.2.1
watson-iot
grid
msbi
css-selectors
multipartform-data
hibernate-mapping
zabbix
pdf-generation
ephesoft
wkhtmltopdf
soap-client
angularjs-ng-repeat
rename
google-app-maker
angular-universal
vichuploaderbundle
expo
cakephp-2.0
luis
loss
orange
android-wifi
datazen-server
gulp-jshint
proof-general
windows-10-mobile
mobile-development
apm
openoffice-impress
urhosharp
circle
flickr
ragel
kofax
lighting
abide
scip
stochastic-process
dotnetnuke-module
libconfig
instances
bzip2
peerjs
smooth-streaming
ocpjp
encoder
jks
stream-socket-client
confluent
stanford-nlp-server
jenkins-docker
intermediate-language
android-vectordrawable
nls
recursive-query
ownership
indoor-positioning-system
alfred
xcode7.1
normalisation
cherry-pick
queuing
avi
3d-rendering
radar-chart
bbedit
video-embedding
libgcrypt
tess4j
joomla3.3
borland-c++
iphone-6
tigase
ios-enterprise
time-frequency
rssi
power-management
slimscroll
pthreads-win32
nativequery
node-amqp
mysql-error-1146
ojb
ia-32
oc4j
jython-2.5
backbone-views
dd4t
uikit-dynamics
select2-rails
qmainwindow
feincms
doxia
motorola-droid
jqzoom
xhtmlrenderer
n2
cryptolicensing
html5-animation
qprocess
calendarextender
authkit
file-icons
jgrowl
jettison

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App