태그 보관물: asp.net

asp.net

C #에서 List <>의 개체를 업데이트하는 방법

나는이 List<>사용자 정의 개체를.

이 목록에서 고유 한 속성으로 개체를 찾고이 개체의 다른 속성을 업데이트해야합니다.

가장 빠른 방법은 무엇입니까?



답변

Linq를 사용하여 수행 할 수있는 개체를 찾습니다.

var obj = myList.FirstOrDefault(x => x.MyProperty == myValue);
if (obj != null) obj.OtherProperty = newValue;

그러나이 경우 목록을 사전에 저장하고 대신 사용할 수 있습니다.

// ... define after getting the List/Enumerable/whatever
var dict = myList.ToDictionary(x => x.MyProperty);
// ... somewhere in code
MyObject found;
if (dict.TryGetValue(myValue, out found)) found.OtherProperty = newValue;


답변

CKoenig의 응답에 추가하기 위해. 그의 대답은 당신이 다루는 클래스가 (클래스와 같은) 참조 유형 인 한 작동합니다. 사용자 지정 개체가 구조체 인 경우 이것은 값 형식이고의 결과는 .FirstOrDefault해당 로컬 복사본을 제공하므로 다음 예제와 같이 컬렉션에 다시 유지되지 않습니다.

struct MyStruct
{
    public int TheValue { get; set; }
}

테스트 코드 :

List<MyStruct> coll = new List<MyStruct> {
                                            new MyStruct {TheValue = 10},
                                            new MyStruct {TheValue = 1},
                                            new MyStruct {TheValue = 145},
                                            };
var found = coll.FirstOrDefault(c => c.TheValue == 1);
found.TheValue = 12;

foreach (var myStruct in coll)
{
    Console.WriteLine(myStruct.TheValue);
}
Console.ReadLine();

출력은 10,1,145입니다.

구조체를 클래스로 변경하면 출력은 10,12,145입니다.

HTH


답변

또는 linq없이

foreach(MyObject obj in myList)
{
   if(obj.prop == someValue)
   {
     obj.otherProp = newValue;
     break;
   }
}


답변

시도 할 수도 있습니다.

 _lstProductDetail.Where(S => S.ProductID == "")
        .Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();


답변

var itemIndex = listObject.FindIndex(x => x == SomeSpecialCondition());
var item = listObject.ElementAt(itemIndex);
item.SomePropYouWantToChange = "yourNewValue";


답변

다음과 같이 할 수 있습니다.

if (product != null) {
    var products = Repository.Products;
    var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
    Repository.Products[indexOf] = product;
    // or 
    Repository.Products[indexOf].prop = product.prop;
}


답변

이것은 오늘 새로운 발견이었습니다-수업 / 구조물 참조 강의를 배운 후에!

Single이 변수를 반환하기 때문에 항목을 찾을 수 있다는 것을 알고 있으면 Linq 및 “Single”을 사용할 수 있습니다 .

myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;