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

Cross-thread operation not valid: Control 'textbox' accessed from a thread other than the thread it was created on
Passport authentication via reddit in asp net?
Azure Mobile App Service not picking up routes
How to find the index of a root folder in a treeview?
how to change image button dynamic in namespace vuforia
Is it possible to mark permanently certain past day in Calendar view with some color or somehow
How to access NSMutableArray index Xamarin.ios
Code First calling a stored procedure passing in 3 params validation errors
Retrieve privileges using security role rather than using system user
Not able to export datatable having 150+ columns to PDF using itextsharp
Nunit console - not working for Xamarin android
WPF - ListView scroll like movie credits
How to resolve dependency in Web API constructor in .net core
Is this the correct usage of a static HttpClient when multithreading?
IZENDA report on ASP.NET MVC application for binary image data convertion
ASP.NET MVC - Displaying the Same View again with extra information based on a radio-button selection

Categories

HOME
classification
grizzly
kendo-ui
microcontroller
jquery-plugins
itext7
pandoc
ms-access-2010
powerquery
browserstack
restheart
adroitlogic
drush
mbed
restructuredtext
serenity-js
rndis
quality-center
poisson
uibarbuttonitem
dynamics-ax-2012-r3
arp
login-required
node-soap
microstrategy
webspeech-api
angularjs-resource
wit-ai
ansible-inventory
cache-control
scip
lfe
server-side-swift
ui-grid
rexx
django-cors-headers
jks
text-formatting
spring-cloud-bus
lucee
perldoc
intermediate-language
qudpsocket
vga
particle-system
git-cherry-pick
cherry-pick
pebble-js
treelist
innertext
web-optimization
code-translation
containstable
std
ios8-share-extension
angular-promise
windows-phone-8-emulator
tooltwist
grails-3.0.9
stderr
jad
xmla
indices
cordova-3
conditional-comments
register-allocation
sync
dotcmis
pyalgotrade
power-management
fastcgi-mono-server
mdp
xcode5.1
grunt-contrib-imagemin
bho
system.transactions
volatility
states
beep
parsec
advanceddatagrid
overlays
windows-xp-embedded
lightopenid
cryptolicensing
datarelation
qprocess
dynamic-scope
stackless

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