54 lines
No EOL
1.5 KiB
C#
54 lines
No EOL
1.5 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using JetBrains.Annotations;
|
|
|
|
namespace JD.Pickers.PickerControls
|
|
{
|
|
public class ViewModelCollection<TModel, TViewModel> : IEnumerable<TViewModel>
|
|
{
|
|
private readonly Dictionary<TViewModel, TModel> _viewToModel;
|
|
private readonly Dictionary<TModel, TViewModel> _modelToView;
|
|
|
|
public ViewModelCollection(IEnumerable<TModel> items, Func<TModel, TViewModel> createViewModel)
|
|
{
|
|
_viewToModel = items.ToDictionary(createViewModel);
|
|
_modelToView = _viewToModel.ToDictionary(pair => pair.Value, pair => pair.Key);
|
|
}
|
|
|
|
[CanBeNull]
|
|
public TViewModel GetViewModel(TModel model)
|
|
{
|
|
TViewModel viewModel;
|
|
if (_modelToView.TryGetValue(model, out viewModel))
|
|
{
|
|
return viewModel;
|
|
}
|
|
|
|
return default(TViewModel);
|
|
}
|
|
|
|
[CanBeNull]
|
|
public TModel GetModel(TViewModel viewModel)
|
|
{
|
|
TModel model;
|
|
if (_viewToModel.TryGetValue(viewModel, out model))
|
|
{
|
|
return model;
|
|
}
|
|
|
|
return default(TModel);
|
|
}
|
|
|
|
public IEnumerator<TViewModel> GetEnumerator()
|
|
{
|
|
return _modelToView.Values.GetEnumerator();
|
|
}
|
|
|
|
IEnumerator IEnumerable.GetEnumerator()
|
|
{
|
|
return GetEnumerator();
|
|
}
|
|
}
|
|
} |