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

Read array of integers from user which is separated by space in C#
WPF DataContext issue
How to delete a Member in a “JsonArray” if I only know its “UniqiueId”?
Geometry instancing in Silverlight 5.0 - is it possible?
How do you add a link to Label text in Xaml?
Sitecore NotificationProvider.GetNotifications is empty
Passing type parameter to generic type with no constraints is throwing a constraint exception
c# set active menu on a tree list from bottom up
How to modify multiple rows in a text file?
Openfiledailog box without using Microsoft.Win32
Data Binding and UI
How to add a hidden field inside webgrid column in MVC action
How to incorporate Multiple languages in a single os?
Visual Studio 2015 Enterprise - Blank XAML App
C#, mssing some data from serial port?
Input string was not in a correct format. Convert.ToInt32(variable)

Categories

HOME
http
marie
alasql
domain-driven-design
python-requests
readdir
azure-database-mysql
itext7
ubuntu-14.04
confluence-rest-api
jshell
rtc
elastalert
aspectj
adroitlogic
console-application
webseal
openstack-horizon
appsettings
background-image
cucumberjs
airbnb
spring-webflow
lotusscript
multipart
beaker-notebook
ng-tags-input
stack-trace
hierarchical-data
typeclass
meteor-accounts
mobile-development
undo
edsdk
wercker
apache-falcon
bootcamp
odp.net
rythm
pygraphviz
lex
file-conversion
sknode
logan-square
serverless-architecture
geminabox
stream-socket-client
jenkins-docker
r-commander
android-vectordrawable
scanf
blackberry-webworks
toggleclass
ldd
geokit
scriptengine
key-value-store
syslog4j
android-xmlpullparser
django-taggit
boost-bind
sqlxml
stdlist
nugetgallery
trendline
firefox-os
computability
android-contentresolver
magnet-uri
musicbrainz
pushwoosh
joomla3.3
playn
android-networking
esb-toolkit-2.1
parseexception
connection-timeout
douglas-peucker
jsonschema2pojo
mind-manager
qf-test
clearcanvas
growl
ccmenuitem
rpt
ant-contrib
dateadd
enquire.js
image-preloader
pidgin
object-oriented-database
db2-connect
mdp
google-voice
misfire-instruction
sygic
playing-cards
wpa
wpd
cloudmade
antixsslibrary
zepto
m3u
beep
bash4
symfony-1.2
azure-appfabric
chars
google-local-search
appointment
office-2003

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