나는이 문제를 제대로 해결하지 못하고 목록에 중복 항목을 추가 할 수없는 이유를 이해할 수 없다고 생각합니다.중복 목록 방지 <T> 항목
동일한 위치에서 동일한 파일을 드래그하더라도 문 조건은 충족되지 않습니다. "Contains"방법이 왜 일치하지 않는지 이해할 수 없습니다.
public class Form1:Form {
private List<FileInfo> dragDropFiles = new List<FileInfo>();
private void Form1_DragDrop(object sender, DragEventArgs e) {
try {
if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
string[] files =
(string[])e.Data.GetData(DataFormats.FileDrop);
OutputDragDrop(files);
}
}
catch { }
}
private void Form1_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void OutputDragDrop(string[] files) {
try {
foreach (string file in files) {
FileInfo fileInfo = new FileInfo(file);
if (dragDropFiles.Contains(fileInfo)) {
dragDropFiles.Remove(fileInfo);
}
dragDropFiles.Add(fileInfo);
}
PopulateContextMenu();
}
catch { }
}
}
는 내가 달성하기에 다른 방법을 발견했다고 생각이
그러나, 제외하고, checkedDragDropFiles
& dragDropFiles
중복을 포함한 항목의 동일한 금액을 표시하여 "고유" dragDropFiles
이 ListBox
에 표시되면 표시되지 않습니다. 왜 이렇게합니까?
목록 데이터를 기반으로 메뉴를 프로그래밍 방식으로 작성하므로 중복 된 목록 항목을 방지해야합니다.
private void OutputDragDrop(string[] files)
{
try
{
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
//if (dragDropFiles.Contains(fileInfo))
//{
// dragDropFiles.Remove(fileInfo);
//}
dragDropFiles.Add(fileInfo);
}
List<FileInfo> checkedDragDropFiles = dragDropFiles.Distinct().ToList();
debugList.DataSource = checkedDragDropFiles;
debugList2.DataSource = dragDropFiles;
//PopulateContextMenu();
}
catch { }
}
무엇이'FileInfo's를 동일하게 만들었습니까?'IEqualityComparer'을 구현하면됩니다. –
Jodrell
'Contains'가 _true_를 반환한다면 왜 제거하고 추가해야합니까? 음수 검사를 수행하고 목록에 값이 들어 있지 않으면 _ 추가하십시오. – Oded
Oded : 좋은 지적입니다. 다소 낭비되는 행동입니다. – negligible