C#序列选择

时间:2009-12-14 21:37:52

标签: c# linq

我想找到 CustomerData 的任何 intColl 长度为单位数,并选择该customerData。

List<CustomerData> cdata = new List<CustomerData>();

cdata.Add(
           new CustomerData { Key = 1, Name = "Marc",
                              intColl = new List<int>() { 1, 2, 3 }
                             }
         );


cdata.Add(
           new CustomerData { Key = 2, Name = "Eric",
                             intColl = new List<int>() { 11, 12, 13 }
                            }
         );


cdata.Add(
           new CustomerData { Key = 3, Name = "Peter", 
                              intColl = new List<int>() { 111, 112, 113 }
                             }
         );  


cdata.Add(
            new CustomerData { Key = 4, Name = "Peter",
                               intColl = new List<int>() { 1111, 1112, 1113 }
                             }
          );

执行以下

var query = cdata.Any(d => d.intColl.Find(c => c == 1));

我收到了

Cannot implicitly convert type 'int' to 'bool'.

2 个答案:

答案 0 :(得分:7)

虽然你写的查询应该写成,

var query = cdata.Any(d => d.intColl.Contains(1));

我认为,根据您的问题文本,您应该这样做:

var query = cdata.Any(d => d.intColl.Any(c => c < 10 && c >= 0));

并返回实际对象(根据评论):

var query = cdata.FirstOrDefault(d => d.intColl.Any(c => c < 10 && c >= 0));
if (query == null) { /* nothing fits the criteria */ }
else { /* use `query` object */ }

答案 1 :(得分:1)

不确定我是否关注你。可能是这样的:

var query = cdata.Where(cd => cd.intColl.Any(i => i<10)); //assuming no negatives

或者这个:

var query = cdata.Where(cd => cd.intColl.Length < 10);