.NET Framework - Linq. Select
Asked By shapper
07-Feb-09 11:39 PM
Hello,
I have the following code:
article.TagsCsv = String.Join(", ", article.Tags.Select(t =>
t.Name).ToArray());
If picks all the tags on an article, joins them, and place the CSV
result in the property TagsCsv.
I am trying to do the same but for many articles:
articles.Select(a => a.TagsCsv = String.Join(", ", a.Tags.Select
(t => t.Name).ToArray()));
This is not working.
What am I doing wrong?
Thanks,
Miguel
LINQ
(1)
Enumerable.Select
(1)
GetEnumerator
(1)
Enumerable
(1)
SelectMany
(1)
ToArray
(1)
Visual
(1)
ToList
(1)
Pavel Minaev replied...
=3D>
.Select
What exactly are you trying to do, and what exactly do you mean by
foreach would do:
foreach (var a in articles) { a.TagsCsv =3D ... }
Select() is _not_ a general purpose replacement for foreach. It's
supposed to be used for projection operations, not to perform some
action for all elements of the sequence.
Or are you trying to build a _single_ CSV string from tags of several
acticles? In this case, use SelectMany:
String.Join(", ", articles.SelectMany(a =3D> a.Tags.Select(t =3D>
t.Name)).ToArray())
shapper replied...
=3D>
gs.Select
No,
I am only trying to fill the property TagsCsv in each Article from its
Tags property.
I now I could use a for loop but I would also like to know how to make
this using Linq. Isn't it possible?
When I say that is not working is that after I apply my code line
TagsCsv keeps being null.
Thanks,
Miguel
Pavel Minaev replied...

It is possible, but highly not desirable. LINQ and expressions with
side effects (this includes all kinds of statements) do not mix well.
To reiterate: if you need to _perform some action_ on each element of
a collection, you should use foreach - that's what it is designed for
(and what LINQ is _not_ designed for). If you need to project, filter,
order, or otherwise process a sequence, getting a _new_ sequence as a
result of the operation, only then you should use LINQ.
From MSDN documentation for Enumerable.Select (and most other methods
of class Enumerable):
return value is an object that stores all the information that is
required to perform the action. The query represented by this method
is not executed until the object is enumerated either by calling its
GetEnumerator method directly or by using foreach in Visual C# or For
Each in Visual Basic."
What happens here is that when you call select, it just remembers the
collection on which Select was called, and the lambda that you passed.
It does not do anything until you start enumerating the result;l and
if you never enumerate it - such as your case here, where you just
throw it away - it's not going to do anything. Even if you start
enumerating it, it will try to be as lazy as possible (i.e. it will
only call the lambda for those elements of the collection that you
enumerate, and not for all of it).
If you call ToArray() on the return value of Select(), then you'll see
your lambda actully execute for all elements.
And this is precisely what I mean when I say that LINQ is not designed
for such tasks (side-effects). Always use side-effect free lambdas
with LINQ, always. If you do, you won't fall into traps like this one,
and you'll be able to switch to PLINQ (or some other optimized LINQ
provider) easily if needed.
Peter Duniho replied...
A reminder: LINQ is not there so that you can solve _every_ programming
problem with it.
As Pavel said, the Enumerable.Select() method isn't intended to be an
alternative to "foreach". In this particular case, what's going on is
that you never attempt to enumerate the collection, so the new enumeration
projected by Select() never even gets realized, so the lambda you provided
to Select() never gets executed.
Thus, nothing happens.
You could fix it by using something like ToArray() or ToList() on the
result of the Select() to force it to evaluate the entire collection. But
really, that's the wrong thing to do, and is just a hack. The right thing
to do is to not abuse the Select() method this way, and instead just use a
regular "foreach" loop.
Pete

axeldahmen.com Axel Dahmen .NET Framework Discussions MyInstance.MyHelpMethod (1) System.Collections.Generic (1) IEnumerable.GetEnumerator (1) Vista (1) Console.KeyAvailable (1) Console.WriteLine (1) SecurityHelper (1) SqlConnection (1) Personally, I they're great - when used appropriately. They can greatly enhance the readability of code, and LINQ is a great example. Which do you think is clearer: 1) Without extension methods: IEnumerable<string> names = Enumerable.Select( (Enumerable.Where(people, person = > person.Age > 17), person = > person.Name); or IEnumerable<string> names = people abused. However, they allow a lot of really *nice* uses too - and enriching interfaces (as LINQ does) is probably the best use going. Of course, you can avoid using them yourself merely your opinion. Many people can and do disagree. One particular example: much of what LINQ provides would not work without extension methods. It relies on it heavily. But regardless, no of OO. Second, extension methods are the least kludgy way to work with objects in LINQ. Without extensions methods, LINQ would be both verbose and rather neutered. Used incorrectly, extension methods become a major cluster
recursive GetEnumerator() .NET Framework Hi, is it possible to have a recursive GetEnumerator for traversing a tree structure ? public IEnumerator<DType> GetEnumerator() { return GetEnumerator(root); } public IEnumerator<DType> GetEnumerator(node p) { if(p.low! = null) GetEnumerator(p.low); yield return p.val; if(p.high! = null GetEnumerator(p.high); } compiles ok, but foreach only does 1 iteration. Colin = ^.^ = C# Discussions GetEnumerator (1) MoveNext (1) Comparer (1) Console (1) IEnumerable (1) IEnumerator (1) WindowsApplication1 (1) DType (1
LINQ to SQL" and "LINQ to Entity" .NET Framework Hi I do not know these tools ("LINQ to SQL" and "LINQ to Entity"), and I would like some good resources to learn about them. They seem very similar - but from what I gather, LINQ to Entity is more complex, and more of an OR / M tool than LINQ to SQL is. Which would be the best to concentrate on, given that I have How do they stack up against NHibernate? Thank you, Peter .NET Framework Discussions NHibernate (1) LINQ (1) Enitity (1) And is it called "LINQ to Enitity" or "LINQ to Entities"? keywords: "LINQ, to, SQL", and, "LINQ, to, Entity" description
populate a DataSet via a LINQ query (Linq to XML) .NET Framework Is there a way to populate a DataSet via a LINQ query? (Linq to XML) Instead of; DataSet ds = new DataSet(); ds.ReadXml(myfile.xml, XmlReadMode.InferTypedSchema); dataGridView1 DataMember = "myNode"; Anthony C# Discussions XmlReadMode (1) OrderByDescending (1) EventArgs (1) XDocument (1) DataGrid (1) LINQ (1) ColumnHeaderMouseClick (1) Attribute (1) You use a Linq-2-XML query and just bind the Linq query results to the control. You can do that. You do not need a dataset How can i bind the Linq query results to the control ? Anthony it is in the link. http: / / blogs.techrepublic.com