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";
LINQ to SQL was the first object-relational mapping technology released by Microsoft. It works well in basic scenarios and continues to be supported in Visual Studio, but it's no longer under active development.
LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.
LINQ allows us to write query against all data whether it comes from array, database, XML etc.
LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code.
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);
}
}
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.
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
Interestingly I didn't assign the result back to ordersList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With