6

This may be a stupid question but I've always used linq to select items.

But i wish to know if it possible to do the following simple task using its keywords.

List<OrdersInfo> ordersList
.
.
.
foreach(OrdersInfo OI in ordersList)
        if(OI.TYPE == "P")
            OI.TYPE = "Project";
        else
        OI.TYPE = "Support";
AngelicCore
  • 1,413
  • 3
  • 22
  • 40

4 Answers4

6

You can use ForEach method of List class.

ordersList.ForEach(oi => oi.TYPE = oi.TYPE == "P" ? "Project" : "Support" );

If you want have ForEach method in IEnumerable type you can create your own ForEach extension

public static void ForEach<T>(this IEnumerable<T> en, Action<T> action)
{
    foreach(T item in en)
    {
        action(item);
    }
}
binard
  • 1,726
  • 1
  • 17
  • 27
5

No, LINQ(Language-Integrated Query) is a query language and it really shines in consise query definition, but not always good in that too (speed and/or memory concerns).

If you want to modify collection, stay with the way you already do that.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 1
    Tigran, I do agree with most part of your answer, but You can modify the list using LINQ. (Although shouldn't) – Habib Apr 24 '13 at 12:05
1

LINQ is for querying collection, For modification your current loop is more readable and better approach, but if you want LINQ option then:

If OrderInfo is a class (reference type), then you can modify the properties of the object, (You can't assign them null or a new references).

var ordersList = new List<OrdersInfo>();
ordersList.Add(new OrdersInfo() { TYPE = "P" });
ordersList.Add(new OrdersInfo() { TYPE = "S" });
ordersList.Add(new OrdersInfo() { TYPE = "P" });
ordersList.Select(r => (r.TYPE == "P" ? r.TYPE = "Project" : r.TYPE = "Support")).ToList();

With Your class defined as:

class OrdersInfo
{
    public string TYPE { get; set; }
}

Here is the screenshot enter image description here

Interestingly I didn't assign the result back to ordersList

Habib
  • 219,104
  • 29
  • 407
  • 436
  • Not sure about a syntactical mistake, probably the mistake is showing somebody how to do this using LINQ? – user7116 Apr 24 '13 at 12:53
  • @sixlettervariables, syntatically its correct, I actually tested it in VS. I agree it shouldn't be done through LINQ and I have that as well in the start of my answer, but being downvoted for showing if it is possible... hmm . thats new for me :) – Habib Apr 24 '13 at 12:56
  • Folks get downvoted all the time for code which "works" but has XSS/SQL injection problems, etc. – user7116 Apr 24 '13 at 13:01
1

ForEach is not a Linq solution, but it looks like it is:

ordersList.ForEach(OI => OI.TYPE = OI.TYPE == "P" ? "Project" : "Support");

Available ony on List<T> instance, not on IEnumerable<T>.

Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122