我在检查列表相等性时遇到问题。 我有以下列表:
List<RequestDetailViewModel> requestDetail
RequestDetailViewModel是:
public int PropertiesValueID { get; set; }
public int UnitID { get; set; }
public string Value { get; set; }
public int PropertyID { get; set; }
我有另一个列表“reqList”:
var reqList = (from p in db.RequestDetail
group new
{ p.PropertyID, p.UnitID , p.Value , p.PropertiesValueID }
by p.RequestID into reqG
select reqG
);
我想检查列表相等性像这样:
foreach (var item in reqList)
{
if (requestDetail equals item)
{
return true;
}
}
我该如何解决这个问题?
答案 0 :(得分:2)
Modify your reqList select:
var reqList = (from p in db.RequestDetail
group new
{ p.PropertyID, p.UnitID , p.Value , p.PropertiesValueID }
by p.RequestID into reqG
select new RequestDetailViewModel{
PropertyID = reqG.PropertyID, UnitID = reqG.UnitID ,
Value = reqG.Value ,
PropertiesValueID = reqG.PropertiesValueID
});
Will return List<RequestDetailViewModel>
Implement IComparable
for your RequestDetailViewModel
class then use SequenceEqual
to compare two lists
答案 1 :(得分:0)
Why don't you loop your View Model list, linq-querying the domain list for each item. Something like:
foreach (var detail in requestDetail)
{
var reqListEqualItems = (from p in db.RequestDetail
where p.PropertyID == details.PropertyID &&
p.UnitID == details.UnitID &&
p.Value == details.Value &&
p.PropertyID == details.PropertyID);
}
Something like that should give you the Domain Object items for each ViewModel item.
答案 2 :(得分:0)
I would update the RequestDetailViewModel
as follows:
public class RequestDetailViewModel : INotifyPropertyChanged
{
private ResultDetail resultDetail;
public RequestDetailViewModel(ResultDetail resultDetail)
{
this.resultDetail = resultDetail;
}
public ResultDetail
{
get
{
return this.resultDetail;
}
}
public int PropertiesValueID
{
get
{
return this.resultDetail.PropertiesValueID;
}
set
{
this.resultDetail.PropertiesValueID = value;
this.RaisePropertyChanged("PropertiesValueID");
}
}
public int UnitID
{
get
{
return this.resultDetail.UnitID ;
}
set
{
this.resultDetail.UnitID = value;
this.RaisePropertyChanged("UnitID");
}
}
public string Value
{
get
{
return this.resultDetail.Value;
}
set
{
this.resultDetail.Value= value;
this.RaisePropertyChanged("Value");
}
}
public int PropertyID
{
get
{
return this.resultDetail.PropertyID ;
}
set
{
this.resultDetail.PropertyID = value;
this.RaisePropertyChanged("PropertyID");
}
}
}
I'd also implement IEquatable in your DB model. and I'd do the check like this:
foreach (var item in reqList)
{
if (requestDetail.ResultDetail.Equals(item))
{
return true;
}
}
or better yet
return reqList.Any(item=> item.Equals(requestDetail.ResultDetail));