简体   繁体   中英

Distinct the collection in Linq C#

I have the collection

From the collection the column name ma_position_value should not contain the same value

For Example

If the collection have 5 records, The column ma_position_value should not contain the same value from all 5 records...but it can contain same value for 2 or 3 or 4 records from the collection Atleast one column value should change.

So the main intension is ALL 5 records should not contain same value.Any one should get different value.So if all 5 is same I tried to throw a message

So I have just write a bool to return it if it is change

bool lblMa = false;
lblMa = ibusCalcWiz.iclbMssPaServiceSummary
        .Where(lbusMssPaServiceSummary => lbusMssPaServiceSummary.icdoSummary.ma_position_value.IsNotNullOrEmpty()).Distinct().Count() > 1;

But it is always return true.

Just select distinct ma_position_value property values:

bool allSame = ibusCalcWiz.iclbMssPaServiceSummary
                          .Select(i => i.ma_position_value)
                          .Distinct()
                          .Count() == 1;

HINT: Do not use long variable names in lambda expressions. There is a rule of thumb - the bigger scope of variable usage, the bigger should be name. If scope is very small (lambda expression) then name should be very small (single letter is enough).

You can get the first one, and check if they are all equal:

// Only works if the collection is non-empty!
string first_ma_position_value = ibusCalcWiz.iclbMssPaServiceSummary.First().ma_position_value;
bool allTheSame = ibusCalcWiz.iclbMssPaServiceSummary
   .All(lbusMssPaServiceSummary.icdoSummary.ma_position_value == first_ma_position_value);

or you can do the distinct, as you originally wanted, but on the value of the column instead of on the objects

bool allTheSame = ibusCalcWiz.iclbMssPaServiceSummary
               .Select(lbusMssPaServiceSummary => lbusMssPaServiceSummary.icdoSummary.ma_position_value)
               .Distinct()
               .Count() == 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM