목록 항목을 가장 좋은 방법으로 바꾸는 방법
if (listofelements.Contains(valueFieldValue.ToString()))
{
listofelements[listofelements.IndexOf(valueFieldValue.ToString())] = value.ToString();
}
나는 위와 같이 교체했습니다. 이것보다 비교할 수있는 다른 최선의 방법이 있습니까?
Lambda를 사용하여 목록에서 인덱스를 찾고이 인덱스를 사용하여 목록 항목을 바꿉니다.
List<string> listOfStrings = new List<string> {"abc", "123", "ghi"};
listOfStrings[listOfStrings.FindIndex(ind=>ind.Equals("123"))] = "def";
더 읽기 쉽고 효율적으로 만들 수 있습니다.
string oldValue = valueFieldValue.ToString();
string newValue = value.ToString();
int index = listofelements.IndexOf(oldValue);
if(index != -1)
listofelements[index] = newValue;
인덱스를 한 번만 요청합니다. 귀하의 접근 방식은 Contains모든 항목을 반복 해야하는 (최악의 경우) 먼저 사용 IndexOf하고 항목을 다시 열거하는 데 필요한 것을 사용 합니다.
한 요소를 대체하기 위해 목록에 두 번 액세스하고 있습니다. 간단한 for루프로 충분 하다고 생각합니다 .
var key = valueFieldValue.ToString();
for (int i = 0; i < listofelements.Count; i++)
{
if (listofelements[i] == key)
{
listofelements[i] = value.ToString();
break;
}
}
확장 방법을 사용하지 않는 이유는 무엇입니까?
다음 코드를 고려하십시오.
var intArray = new int[] { 0, 1, 1, 2, 3, 4 };
// Replaces the first occurance and returns the index
var index = intArray.Replace(1, 0);
// {0, 0, 1, 2, 3, 4}; index=1
var stringList = new List<string> { "a", "a", "c", "d"};
stringList.ReplaceAll("a", "b");
// {"b", "b", "c", "d"};
var intEnum = intArray.Select(x => x);
intEnum = intEnum.Replace(0, 1);
// {0, 0, 1, 2, 3, 4} => {1, 1, 1, 2, 3, 4}
- 중복 된 코드 없음
- 긴 linq 표현식을 입력 할 필요가 없습니다.
- 추가로 사용할 필요가 없습니다.
소스 코드 :
namespace System.Collections.Generic
{
public static class Extensions
{
public static int Replace<T>(this IList<T> source, T oldValue, T newValue)
{
if (source == null)
throw new ArgumentNullException("source");
var index = source.IndexOf(oldValue);
if (index != -1)
source[index] = newValue;
return index;
}
public static void ReplaceAll<T>(this IList<T> source, T oldValue, T newValue)
{
if (source == null)
throw new ArgumentNullException("source");
int index = -1;
do
{
index = source.IndexOf(oldValue);
if (index != -1)
source[index] = newValue;
} while (index != -1);
}
public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T newValue)
{
if (source == null)
throw new ArgumentNullException("source");
return source.Select(x => EqualityComparer<T>.Default.Equals(x, oldValue) ? newValue : x);
}
}
}
The first two methods have been added to change the objects of reference types in place. Of course, you can use just the third method for all types.
P.S. Thanks to mike's observation, I've added the ReplaceAll method.
Following rokkuchan's answer, just a little upgrade:
List<string> listOfStrings = new List<string> {"abc", "123", "ghi"};
int index = listOfStrings.FindIndex(ind => ind.Equals("123"));
if (index > -1)
listOfStrings[index] = "def";
Use FindIndex and lambda to find and replace your values:
int j = listofelements.FindIndex(i => i.Contains(valueFieldValue.ToString())); //Finds the item index
lstString[j] = lstString[j].Replace(valueFieldValue.ToString(), value.ToString()); //Replaces the item by new value
I don't if it is best or not but you can use it also
List<string> data = new List<string>
(new string[] { "Computer", "A", "B", "Computer", "B", "A" });
int[] indexes = Enumerable.Range(0, data.Count).Where
(i => data[i] == "Computer").ToArray();
Array.ForEach(indexes, i => data[i] = "Calculator");
Or, building on Rusian L.'s suggestion, if the item you're searching for can be in the list more than once::
[Extension()]
public void ReplaceAll<T>(List<T> input, T search, T replace)
{
int i = 0;
do {
i = input.FindIndex(i, s => EqualityComparer<T>.Default.Equals(s, search));
if (i > -1) {
FileSystem.input(i) = replace;
continue;
}
break;
} while (true);
}
I thinks it's better to use ObservableCollection instead of List, and convert it to a list when we need to range it. with observable collection you can remove and add element in two line, but you have to code a dozen of line to get this functionality using a list. this link may give a clear idea about ObservableCollection<> vs. List<>
i find best for do it fast and simple
find ur item in list
var d = Details.Where(x => x.ProductID == selectedProduct.ID).SingleOrDefault();make clone from current
OrderDetail dd = d;Update ur clone
dd.Quantity++;find index in list
int idx = Details.IndexOf(d);remove founded item in (1)
Details.Remove(d);insert
if (idx > -1) Details.Insert(idx, dd); else Details.Insert(Details.Count, dd);
참고URL : https://stackoverflow.com/questions/17188966/how-to-replace-list-item-in-best-way
'program story' 카테고리의 다른 글
| TypeScript에서 배열 선언 (0) | 2020.10.18 |
|---|---|
| 연결이 로컬 호스트인지 javascript로 확인하는 방법은 무엇입니까? (0) | 2020.10.18 |
| Espresso에 대화 상자가 표시되는지 확인 (0) | 2020.10.18 |
| Chrome 기기 모드 에뮬레이션 미디어 쿼리가 작동하지 않음 (0) | 2020.10.18 |
| 배열 또는 목록이 기본적으로 C #에서 참조로 전달됩니까? (0) | 2020.10.18 |