programing

C# 목록 내의 오브젝트를 갱신하는 방법 <>

starjava 2023. 4. 12. 21:40
반응형

C# 목록 내의 오브젝트를 갱신하는 방법 <>

나는 가지고 있다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();

다음과 같은 작업을 수행할 수 있습니다.

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;
}
var itemIndex = listObject.FindIndex(x => x == SomeSpecialCondition());
var item = listObject.ElementAt(itemIndex);
item.SomePropYouWantToChange = "yourNewValue";

이것은 수업/구조 레퍼런스 레슨을 배운 후 오늘 새로운 발견이었습니다.

항목을 찾을 수 있는 경우 Linq 및 "Single"을 사용할 수 있습니다. Single은 변수를 반환하므로...

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

LINQ의 코드 unsing에서 이 작업을 수행할 수 있는 방법을 찾았습니다.

yourList.Where(yourObject => yourObject.property == "yourSearchProperty").Select(yourObject => { yourObject.secondProperty = "yourNewProperty"; return yourObject; }).ToList();
var index = yourList.FindIndex(x => x.yourProperty == externalProperty);
if (index > -1)
{
   yourList[index] = yourNewObject;   
}

이제 목록 안에 업데이트된 개체가 있습니다.

매트 로버츠가 말한 것이 교실 내 구조에도 적용된다는 것도 언급할 가치가 있다.

따라서 클래스(이론적으로 참조로 전달됨)가 있는 경우에도 해당 클래스 내의 구조 목록인 속성은 특정 구조체 내에서 값을 찾고 변경하려고 하면 값별로 전달됩니다.

예를 들어 (Matt가 제안한 것과 동일한 코드를 사용):

ParentClass instance = new ParentClass();

var found = instance.ListofStruct.FirstOrDefault(c => c.TheValue == 1);
found.TheValue = 12;

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

public class ParentClass
{
    public List<MyStruct> ListofStruct { get; set; }
    public struct MyStruct
    { 
        public int TheValue { get; set; }
    }

    public ParentClass()
    {
        ListofStruct = new List<MyStruct>()
        {
            new MyStruct {TheValue = 10},
            new MyStruct {TheValue = 1},
            new MyStruct {TheValue = 145}
        };
    }
}

Will 출력: 10, 1, 145

한편, 다음과 같이 구조(ParentClass 내부)를 클래스로 변경합니다.

public class ParentClass
{
    public List<MySubClass> ListofClass { get; set; }
    public class MySubClass
    {
        public int TheValue { get; set; }
    }

    public ParentClass()
    {
        ListofClass = new List<MySubClass>()
        {
            new MySubClass {TheValue = 10},
            new MySubClass {TheValue = 1},
            new MySubClass {TheValue = 145}
        };
    }
}

Will 출력: 10, 12, 145

//Find whether the element present in the existing list

    if (myList.Any(x => x.key == "apple"))
       {
          //Get that Item
         var item = myList.FirstOrDefault(x => x.key == ol."apple");
        //update that item
         item.Qty = "your new value";
       }

언급URL : https://stackoverflow.com/questions/7190016/how-to-update-an-object-in-a-list-in-c-sharp

반응형