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

Am I using ContinueWith correctly?
Load multiple methods from dll at runtime C#
bind images in buttons in a FlipView windows app store
Efficient way of shifting row down in ASP table
How to run DirectX code samples on Visual Studio 2015 and Windows 10?
How to backup the database from the server to the client computer using asp.net page
How to convert Android.Net.Uri path to physical path in xamarin?
WPF Datagrid has data in the rows but not displaying text
c#.net Word add-in
How to select only content in the sheet rather all unused/empty cell value
Only Half of a Deck of Cards Being Created [closed]
C# string Dictionary sorting
Using ToListAsync on an IQueryable
TFS API Console Application opens and closes
return File (memory stream) encoding
XslCompiledTransform.Transform: pass a list of strings as input parameter and check “input array contains”

Categories

HOME
autohotkey
gsm
compression
mysqli
casting
opencv4android
reference
ebay-api
magento-1.9.2.1
cryengine
pandoc
servicenow
collision-detection
meson-build
browserstack
clip-path
osx-yosemite
soap-client
rename
openbsd
osclass
solidity
dompdf
game-engine
gpo
gomobile
angular2-pipe
smali
matlab-gui
email-client
oracle-golden-gate
datastax-enterprise
grunt-contrib-uglify
utc
scripting-language
ds-5
ios9
log4net-configuration
ports
geocomplete
pyenv
queryover
origami
nsdateformatter
nscollectionview
collation
contenteditable
web-technologies
qt-quick
python-venv
amazon-fire-tv
reqif
activeandroid
runner
androiddesignsupport
try-catch-finally
reloaddata
tsc
therubyracer
portaudio
android-music-player
android-tabs
scikit-image
mate-desktop
camellia
dcast
datamodel
yfiles
gnu-sort
adempiere
tess4j
hexagonal-tiles
dpkt
nmock
pdcurses
nexusdb
xcode5
azure-worker-roles
django-tests
vbaccelerator
netbeans-plugins
pyxplot
google-checkout
qmainwindow
magicsuggest
biztalk-deployment
netzke
jquery-ui-map
erlide
ruby-1.9
digg
lgpl
activescaffold
google-local-search
hp-trim
content-delivery-network
cross-cutting-concerns

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