开发者

LINQ-All condition

I have a Class :

Public Class Task
{
    Public Guid TaskId { get ; set }
    Public Guid ParentId { get ; set }
    ...
}

And Another class :

Public Class ContractDetail
{
    Public Guid Contr开发者_开发技巧actDetailsID {get;set}
    Public Guid TaskId { get;set}
    ...
}

I want to check if all Tasks have ContractDetail then do some thing and I wrote this query:

 List<Guid> Sids = new List<Guid>();
 Sids = Tasks.Where(p => p.ParentId == ParentId).Select(p => p.TaskId).ToList();
 if(ContractDetails.All(p => Sids.Contains(p.TaskId))
 {
      int i = 5;
      .....
 }

But it returns false always.

How to check All of Tasks have ContractDetails or not?


bool allTasksHaveContractDetails = Tasks.All(t => ContractDetails.Any(cd => cd.TaskId == t.TaskId))

Another approach:

var query =
    from t in Tasks
    join cd in ContractDetails on t.TaskId equals cd.TaskId into tmp
    select tmp;

bool allTasksHaveContractDetails = query.All(x => x.Any());


Instead of Contains, try:

Sids.Any(s => s.Equals(p.SakhtarId))

And try to debug it by making sure that this condition should really be true.


I'm not sure if I fully get your usage scenario, but assuming you want to check that for every Task there is an associated ContractDetail, i.e. the ContractDetail and the Task have the same TaskId, you can select the unique ids from both collections and use IEnumerable.SequenceEquals like so:

var tids = tasks.OrderBy(t => t.TaskId).Select(t => t.TaskId).Distinct();
var ctids = details.OrderBy(c => c.TaskId).Select(c => c.TaskId).Distinct();

if (tids.SequenceEqual(ctids))
{
    Console.WriteLine("Every task has a contract");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜