score:11
If you're looking to conditionally project a Foo to another Foo (leaving others untouched), you can do something like:
IEnumerable<Foo> foos = ...
var transformed = foos.Select(foo => myCondition(foo) ? transform(foo) : foo);
On the other hand, if you only want to project Foos that match the condition:
var transformed = foos.Where(foo => myCondition(foo))
.Select(foo => transform(foo));
Do note that both of these return new sequences - LINQ isn't normally used to modify existing collections. You could of course materialize the results into a collection, overwriting an existing variable if necessary.
// assuming the transform is from Foo -> Foo
foos = foos.Select(foo => transform(foo)).ToList();
Since you specifically mention lists, there is another non-LINQ immediate-execution alternative to the first query - the List<T>.ConvertAll
method:
List<Foo> foos = ...
// implicitly List<Foo> assuming the transform is from Foo -> Foo
var transformed = foos.ConvertAll
(foo => myCondition(foo) ? transform(foo) : foo);
EDIT: Sounds like you're looking for a "ReplaceWhere" method - as far as I know, there is no direct framework method that replaces the elements of a list based on a predicate. It's easy to write one yourself though:
/// <summary>
/// Replaces items in a list that match the specified predicate,
/// based on the specified selector.
/// </summary>
public static void ReplaceWhere<T>(this IList<T> list,
Func<T, bool> predicate,
Func<T, T> selector)
{
// null-checks here.
for (int i = 0; i < list.Count; i++)
{
T item = list[i];
if (predicate(item))
list[i] = selector(item);
}
}
Usage:
List<int> myList = ...
myList.ReplaceWhere(i => i > 0, i => i * i);
score:4
You could certainly write a transformation function:
// allows you to transform every element
public static List<T> TransformAll<T>(this List<T> list,
Func<T, T> converter)
{
for (int i = 0; i < list.Count; i++)
{
list[i] = converter(list[i]);
}
return list;
}
// allows you to transform every element based on its index
public static List<T> TransformAll<T>(this List<T> list,
Func<T, int, T> converter)
{
for (int i = 0; i < list.Count; i++)
{
list[i] = converter(list[i], i);
}
return list;
}
// allows you to transform chosen elements
public static List<T> TransformWhere<T>(this List<T> list,
Func<T, bool> predicate,
Func<T, T> converter)
{
for (int i = 0; i < list.Count; i++)
{
T item = list[i];
if (predicate(item))
list[i] = converter(item);
}
return list;
}
// allows you to transform chosen elements based on its index
public static List<T> TransformWhere<T>(this List<T> list,
Func<T, int, bool> predicate,
Func<T, int, T> converter)
{
for (int i = 0; i < list.Count; i++)
{
T item = list[i];
if (predicate(item, i))
list[i] = converter(item, i);
}
return list;
}
Note that I made all my functions return the passed-in list so that you can use them fluently, like list.TransformAll(x => x + 2).Sum()
.
Source: stackoverflow.com
Related Articles
- LINQ Source Code Available
- LINQ Transformation Function
- creating Linq to sqlite dbml from DbLinq source code
- CLRSQL Aggregate function. LINQ Code works within CLR Function but cannot be deploy within Aggregate
- source code for LINQ 101 samples
- LINQ function to return list but compiler says function doesn't return a value on all code path
- c# Linq or code to extract groups from a single list of source data
- How to call an Sql User defined Function using Entity frame work Code first approach with LInq c#
- Convert string[] to int[] in one line of code using LINQ
- Code equivalent to the 'let' keyword in chained LINQ extension method calls
- Apply function to all elements of collection through LINQ
- Linq code to select one item
- How are people unit testing code that uses Linq to SQL
- Is there a LINQ function for getting the longest string in a list of strings?
- LINQ identity function
- Unit test error : This function can only be invoked from LINQ to Entities
- LINQ query to perform a projection, skipping or wrapping exceptions where source throws on IEnumerable.GetNext()
- Syntax to execute code block inside Linq query?
- Calling a SQL User-defined function in a LINQ query
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- How to create a dynamic LINQ select projection function from a string[] of names?
- Best open source LINQ provider
- Is there a simple way to write a custom function in LINQ to Entities?
- LINQ select to new object, setting values of object in function
- Is there a good source that gives an overview of linq optimizations?
- In LINQ to SQL, how do you pass parts of a LINQ query into a function
- Does this LINQ code perform multiple lookups on the original data?
- How to understand the following C# linq code of implementing the algorithm to return all combinations of k elements from n
- LINQ WHERE method alters source collection
- Linq Exception: Function can only be invoked from linq to entities
- Pass Data from controller to view is not responding. Is there something wrong in the code?
- Find objects in list that match elements in array
- Date Difference Logic in LINQ
- IEnumerable.ToArray<T>() vs. IEnumerable.Cast<T>().ToArray()
- How to get <? tags from xml with vb.net
- Transform Linq Data Structure
- Master list filtered from other lists based on matching values
- Casting the value created in LINQ object
- C# search query for comma delimited access database field
- For a database collection, should FirstOrDefault return null?
- Conditional logic for generic filter mechanism for Entity Framework
- Vb Linq "The value can not be null" using Group.FirstOrDefault
- Linq query working in LinqPad but not in VS
- Dynamic Way to Map WebGrid Column Name to OrderBy Lambda Expression
- DataGridVIew populated with anonymous type, how to filter?
- Excel to SQL, C# libraries
- Assign Mapped Object to Expression Result in LINQ to Entities
- LINQ join using Generics
- Paging with GridView and LINQ to SQL
- Split into xml files retaining few tags from base xml file using linq