LINQ를 사용하여 컬렉션의 모든 개체 업데이트
LINQ를 사용하여 다음을 수행하는 방법이 있습니까?
foreach (var c in collection)
{
c.PropertyToSet = value;
}
명확히하기 위해 컬렉션의 각 개체를 반복 한 다음 각 개체의 속성을 업데이트하고 싶습니다.
내 유스 케이스는 블로그 게시물에 대한 의견이 많으며 블로그 게시물의 각 의견을 반복하고 블로그 게시물의 날짜 시간을 +10 시간으로 설정하고 싶습니다. SQL로 할 수는 있지만 비즈니스 계층에 유지하고 싶습니다.
당신이 사용할 수 있지만 ForEach
확장 방법을, 당신은 당신이 할 수있는 단지 프레임 워크를 사용하려는 경우
collection.Select(c => {c.PropertyToSet = value; return c;}).ToList();
게으른 평가ToList
로 인해 선택을 즉시 평가하려면 이 옵션 이 필요합니다 .
collection.ToList().ForEach(c => c.PropertyToSet = value);
나는 이것을하고있다
Collection.All(c => { c.needsChange = value; return true; });
실제로 내가 원하는 것을 할 수있는 확장 방법 을 찾았습니다.
public static IEnumerable<T> ForEach<T>(
this IEnumerable<T> source,
Action<T> act)
{
foreach (T element in source) act(element);
return source;
}
사용하다:
ListOfStuff.Where(w => w.Thing == value).ToList().ForEach(f => f.OtherThing = vauleForNewOtherThing);
이것이 LINQ를 과도하게 사용하고 있는지 확실하지 않지만 특정 조건에 대해 목록의 특정 항목을 업데이트하려고 할 때 효과적이었습니다.
이를위한 내장 확장 방법은 없습니다. 하나를 정의하는 것은 상당히 간단합니다. 게시물 맨 아래에는 Iterate라는 정의 된 방법이 있습니다. 그렇게 사용할 수 있습니다
collection.Iterate(c => { c.PropertyToSet = value;} );
반복 소스
public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T> callback)
{
if (enumerable == null)
{
throw new ArgumentNullException("enumerable");
}
IterateHelper(enumerable, (x, i) => callback(x));
}
public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
if (enumerable == null)
{
throw new ArgumentNullException("enumerable");
}
IterateHelper(enumerable, callback);
}
private static void IterateHelper<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
int count = 0;
foreach (var cur in enumerable)
{
callback(cur, count);
count++;
}
}
나는 이것에 대해 몇 가지 변형을 시도했으며,이 사람의 해결책으로 계속 돌아갑니다.
http://www.hookedonlinq.com/UpdateOperator.ashx
다시, 이것은 다른 누군가의 솔루션입니다. 그러나 코드를 작은 라이브러리로 컴파일하고 상당히 정기적으로 사용합니다.
앞으로 그의 사이트 (블로그)가 더 이상 존재하지 않을 가능성을 높이기 위해 그의 코드를 여기에 붙여 넣을 것입니다. "필요한 답변이 여기에 있습니다", 클릭 및 데드 URL이라는 게시물을 보는 것보다 나쁘지 않습니다.
public static class UpdateExtensions {
public delegate void Func<TArg0>(TArg0 element);
/// <summary>
/// Executes an Update statement block on all elements in an IEnumerable<T> sequence.
/// </summary>
/// <typeparam name="TSource">The source element type.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="update">The update statement to execute for each element.</param>
/// <returns>The numer of records affected.</returns>
public static int Update<TSource>(this IEnumerable<TSource> source, Func<TSource> update)
{
if (source == null) throw new ArgumentNullException("source");
if (update == null) throw new ArgumentNullException("update");
if (typeof(TSource).IsValueType)
throw new NotSupportedException("value type elements are not supported by update.");
int count = 0;
foreach (TSource element in source)
{
update(element);
count++;
}
return count;
}
}
int count = drawingObjects
.Where(d => d.IsSelected && d.Color == Colors.Blue)
.Update(e => { e.Color = Color.Red; e.Selected = false; } );
아닙니다. LINQ는 대량 업데이트 방식을 지원하지 않습니다. 유일한 짧은 방법은 ForEach
확장 방법 을 사용하는 것입니다. IEnumerable에 ForEach 확장 방법이없는 이유는 무엇입니까?
내 두 동전 :-
collection.Count(v => (v.PropertyToUpdate = newValue) == null);
나는 그것을 도울 수있는 확장 방법을 썼다.
namespace System.Linq
{
/// <summary>
/// Class to hold extension methods to Linq.
/// </summary>
public static class LinqExtensions
{
/// <summary>
/// Changes all elements of IEnumerable by the change function
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="change">The way you want to change the stuff</param>
/// <returns>An IEnumerable with all changes applied</returns>
public static IEnumerable<T> Change<T>(this IEnumerable<T> enumerable, Func<T, T> change )
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(change, "change");
foreach (var item in enumerable)
{
yield return change(item);
}
}
/// <summary>
/// Changes all elements of IEnumerable by the change function, that fullfill the where function
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="change">The way you want to change the stuff</param>
/// <param name="where">The function to check where changes should be made</param>
/// <returns>
/// An IEnumerable with all changes applied
/// </returns>
public static IEnumerable<T> ChangeWhere<T>(this IEnumerable<T> enumerable,
Func<T, T> change,
Func<T, bool> @where)
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(change, "change");
ArgumentCheck.IsNullorWhiteSpace(@where, "where");
foreach (var item in enumerable)
{
if (@where(item))
{
yield return change(item);
}
else
{
yield return item;
}
}
}
/// <summary>
/// Changes all elements of IEnumerable by the change function that do not fullfill the except function
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="change">The way you want to change the stuff</param>
/// <param name="where">The function to check where changes should not be made</param>
/// <returns>
/// An IEnumerable with all changes applied
/// </returns>
public static IEnumerable<T> ChangeExcept<T>(this IEnumerable<T> enumerable,
Func<T, T> change,
Func<T, bool> @where)
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(change, "change");
ArgumentCheck.IsNullorWhiteSpace(@where, "where");
foreach (var item in enumerable)
{
if (!@where(item))
{
yield return change(item);
}
else
{
yield return item;
}
}
}
/// <summary>
/// Update all elements of IEnumerable by the update function (only works with reference types)
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="update">The way you want to change the stuff</param>
/// <returns>
/// The same enumerable you passed in
/// </returns>
public static IEnumerable<T> Update<T>(this IEnumerable<T> enumerable,
Action<T> update) where T : class
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(update, "update");
foreach (var item in enumerable)
{
update(item);
}
return enumerable;
}
/// <summary>
/// Update all elements of IEnumerable by the update function (only works with reference types)
/// where the where function returns true
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="update">The way you want to change the stuff</param>
/// <param name="where">The function to check where updates should be made</param>
/// <returns>
/// The same enumerable you passed in
/// </returns>
public static IEnumerable<T> UpdateWhere<T>(this IEnumerable<T> enumerable,
Action<T> update, Func<T, bool> where) where T : class
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(update, "update");
foreach (var item in enumerable)
{
if (where(item))
{
update(item);
}
}
return enumerable;
}
/// <summary>
/// Update all elements of IEnumerable by the update function (only works with reference types)
/// Except the elements from the where function
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="update">The way you want to change the stuff</param>
/// <param name="where">The function to check where changes should not be made</param>
/// <returns>
/// The same enumerable you passed in
/// </returns>
public static IEnumerable<T> UpdateExcept<T>(this IEnumerable<T> enumerable,
Action<T> update, Func<T, bool> where) where T : class
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(update, "update");
foreach (var item in enumerable)
{
if (!where(item))
{
update(item);
}
}
return enumerable;
}
}
}
나는 이것을 다음과 같이 사용하고있다 :
List<int> exampleList = new List<int>()
{
1, 2 , 3
};
//2 , 3 , 4
var updated1 = exampleList.Change(x => x + 1);
//10, 2, 3
var updated2 = exampleList
.ChangeWhere( changeItem => changeItem * 10, // change you want to make
conditionItem => conditionItem < 2); // where you want to make the change
//1, 0, 0
var updated3 = exampleList
.ChangeExcept(changeItem => 0, //Change elements to 0
conditionItem => conditionItem == 1); //everywhere but where element is 1
인수 점검을 참조하십시오.
/// <summary>
/// Class for doing argument checks
/// </summary>
public static class ArgumentCheck
{
/// <summary>
/// Checks if a value is string or any other object if it is string
/// it checks for nullorwhitespace otherwhise it checks for null only
/// </summary>
/// <typeparam name="T">Type of the item you want to check</typeparam>
/// <param name="item">The item you want to check</param>
/// <param name="nameOfTheArgument">Name of the argument</param>
public static void IsNullorWhiteSpace<T>(T item, string nameOfTheArgument = "")
{
Type type = typeof(T);
if (type == typeof(string) ||
type == typeof(String))
{
if (string.IsNullOrWhiteSpace(item as string))
{
throw new ArgumentException(nameOfTheArgument + " is null or Whitespace");
}
}
else
{
if (item == null)
{
throw new ArgumentException(nameOfTheArgument + " is null");
}
}
}
}
LINQ를 사용하여 컬렉션을 배열로 변환 한 다음 Array.ForEach ()를 호출 할 수 있습니다.
Array.ForEach(MyCollection.ToArray(), item=>item.DoSomeStuff());
분명히 이것은 구조체 모음이나 정수 또는 문자열과 같은 내장 유형에서는 작동하지 않습니다.
linq-solution을 특별히 요청했지만이 질문은 꽤 오래되었지만 비 linq-solution을 게시합니다. 이는 linq (= language 통합 쿼리 )가 콜렉션의 쿼리에 사용 되기 때문 입니다. 모든 linq 메소드는 기본 콜렉션을 수정하지 않고 단지 새로운 콜렉션을 리턴 합니다 (또는 더 정확한 반복자를 새로운 콜렉션으로 리턴 합니다). 따라서 예를 들어 무엇을하든 Select
기본 컬렉션에 영향을 미치지 않으면 서 새로운 컬렉션을 얻게됩니다.
물론 당신은 할 수 와 함께 할 ForEach
(길, 그러나 확장에 의해, 어떤 밤은 LINQ List<T>
). 그러나 이것은 문자 그대로foreach
람다 표현과 함께 사용 합니다. 이 외에도에서 모든 LINQ-방법은 내부적으로 사용하여 수집 등을 반복 할 foreach
또는 for
단순히 클라이언트에서 숨 깁니다 그러나. 나는 이것을 더 읽기 쉽고 유지 보수 할 수 있다고 생각하지 않습니다 (람다 식을 포함하는 메소드를 디버깅하는 동안 코드 편집을 생각하십시오).
이 방법으로 Linq를 사용 하여 컬렉션의 항목 을 수정 하지 마십시오 . 더 좋은 방법은 질문에 이미 제공 한 솔루션입니다. 클래식 루프를 사용하면 컬렉션을 쉽게 반복하고 항목을 업데이트 할 수 있습니다. 실제로 모든 의존하는 솔루션 List.ForEach
은 다르지 않지만 제 관점에서 읽기가 훨씬 어렵습니다.
따라서 컬렉션의 요소 를 업데이트 하려는 경우 linq를 사용하지 않아야 합니다.
내가 사용하는 확장 방법은 다음과 같습니다.
/// <summary>
/// Executes an Update statement block on all elements in an IEnumerable of T
/// sequence.
/// </summary>
/// <typeparam name="TSource">The source element type.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="action">The action method to execute for each element.</param>
/// <returns>The number of records affected.</returns>
public static int Update<TSource>(this IEnumerable<TSource> source, Func<TSource> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
if (typeof (TSource).IsValueType)
throw new NotSupportedException("value type elements are not supported by update.");
var count = 0;
foreach (var element in source)
{
action(element);
count++;
}
return count;
}
LINQ의 일괄 작업 프레임 워크 인 Magiq 을 사용할 수 있습니다 .
쿼리 내에서 값을 변경하여 함수를 작성할 수 있다고 가정합니다.
void DoStuff()
{
Func<string, Foo, bool> test = (y, x) => { x.Bar = y; return true; };
List<Foo> mylist = new List<Foo>();
var v = from x in mylist
where test("value", x)
select x;
}
class Foo
{
string Bar { get; set; }
}
그러나 이것이 당신이 의미하는 것이라면 확실하지 않습니다.
아래와 같은 데이터가 있다고 가정 해 봅시다.
var items = new List<string>({"123", "456", "789"});
// Like 123 value get updated to 123ABC ..
목록을 수정하고 목록의 기존 값을 수정 된 값으로 바꾸려면 먼저 빈 목록을 새로 만든 다음 각 목록 항목에서 수정 방법을 호출하여 데이터 목록을 반복합니다.
var modifiedItemsList = new List<string>();
items.ForEach(i => {
var modifiedValue = ModifyingMethod(i);
modifiedItemsList.Add(items.AsEnumerable().Where(w => w == i).Select(x => modifiedValue).ToList().FirstOrDefault()?.ToString())
});
// assign back the modified list
items = modifiedItemsList;
참고 URL : https://stackoverflow.com/questions/398871/update-all-objects-in-a-collection-using-linq
'Programming' 카테고리의 다른 글
C # Guid 값을 만드는 방법? (0) | 2020.02.16 |
---|---|
Java에서 파일의 파일 확장자를 얻으려면 어떻게합니까? (0) | 2020.02.16 |
툴바에 뒤로 화살표 표시 (0) | 2020.02.16 |
각도 지시문-컴파일, 컨트롤러, 사전 링크 및 사후 링크 사용시기 및 방법 [폐쇄] (0) | 2020.02.16 |
사용자 에이전트 스타일 시트 란 무엇입니까 (0) | 2020.02.16 |