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 can I make a C# class instantiate another class in its constructor?
Why does task.Wait not deadlock on a non-ui thread? Or am I just lucky?
Pattern for adding entry and exit trace to a method
How to read single node value from xml file
Display issue with Adobe PDF viewer (i.e. axInterop.AcroPDFLib.dll) in windows 7
(C# WPF SQL Server) Is it possible to connect to the database several times in one function? [closed]
How to do String.Join while deserializing a JSON string?
Per Process monitoring in C#
c# How do I concat a var with another var to point to an application SettingsName?
Add an encoding declaration [closed]
Is it possible to load BCP file to memory in C# with some library class?
Efficient method for checking quality of a sound recording
Ignore a property during xml serialization but not during deserialization
Add a new view to controller
Having trouble binding ViewModel to ComboBox
How to pass difference type into a function like passing variables [closed]

Categories

HOME
excel-formula
postgresql
primefaces
compression
qemu
phantomjs
django-middleware
aggregate-functions
liquidsoap
clip-path
rename
jetbrains
multibinding
taxonomy
draw2d
autologin
hl7-fhir
datasource
restructuredtext
rancher
delphi-2010
folder
foxpro
textview
webclient
apache-falcon
dropdownbox
javafxports
device-driver
ngrok
apiman
text-formatting
stanford-nlp-server
skype-bots
standard-error
jcifs
playframework-1.x
photoshop-script
try-catch-finally
bipartite
codesniffer
recursive-query
indoor-positioning-system
visual-web-developer
access-violation
key-value-store
stdlist
skbio
hana-sql-script
datamodel
clear
gulp-cdnizer
litedb
data-representation
sicstus-prolog
gmaps4jsf
backtrace
indices
caption
javadb
yosemite
ccmenuitem
isl
sendy
netbeans-plugins
friendly-id
symbian3
latex-suite
http-compression
simplemembership
libx264
tasklist
expresso-store
nsscrollview
fileoutputstream
xhtmlrenderer
javah
virtual-destructor
database-agnostic
linq-to-mysql
uccapi
script-tag
opengl-to-opengles
user-preferences
high-load

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile