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

C# Converting 32bpp image to 8bpp
Is there any way to Read/Write object to .csv
How to create new radiobuttonlist with question on submit? c# asp.net
Storing DataRows independently of a DataTable - RowNotInTableException
In MVP, should a form get the object it's going to display in the constructor?
Network stream problem
Is it possible to persist the viewstate between pages in ASP.NET?
Creating a .NET 3.5 version from a .NET 4.0 project
Specified cast is not valid.. how to resolve this
What is the fastest parser generator tool for C# output? [closed]
Process Management in .NET
Issue with self-many to many join in Fluent NHibernate
LINQ-to-XML: Selecting specific node value
OnClient Click javascript using Freetextbox
Please help on choosing the right arhitecture of n-tier web application
Read Excel using c# .net Issue

Categories

HOME
asp.net
ssms
google-cloud-pubsub
gsm
postgresql-9.3
azure-eventhub
webvr
c++builder
itext7
datetimepicker
xss
sugarcrm
comments
servicenow
sha1
powerpivot
jquery-easyui
aiml
gnu-screen
datastax-enterprise
sasl
marionette
setup-project
dynamics-ax-2012-r3
r-factor
foxpro
ng2-bootstrap
choco
circle
flickr
dropdownbox
certbot
android-geofence
mongoid5
libconfig
nscollectionview
fisheye
azure-web-roles
collation
java-5
vpython
reqif
standard-error
critical-section
recursive-query
qt3d
directinput
portaudio
strtol
git-push
syslog4j
change-password
patching
php-java-bridge
diameter-protocol
boost-bind
mod
bbedit
dcast
firefox-os
hana-sql-script
ooad
wonderware
android-contentresolver
bioconductor
dpkt
clearquest
web-standards
targetprocess
tinymce-plugins
sony-xperia
crtdbg.h
iphone-6
fxmlloader
report-builder2.0
ios-enterprise
disabled-control
django-tests
reactjs-native
sendy
smartxls
new-operator
kernel-density
nop
code-complete
raddatepicker
azure-pack
record-locking
xrandr
android-library
dd4t
select2-rails
codeigniter-form-helper
servicemanager
generator-expression
webpage-screenshot
derived-class
certificate-revocation
jquery-ui-map
pex-and-moles
backlight
sipdroid
jexcelapi
zipstream
nbehave
hs-err
iphone-maps
browser-state
for-xml
newspeak
zend-acl
vista64
jettison
moores-law

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile