简体   繁体   中英

How to compare two List<String> using LINQ in C#

The two lists are like

          LISTONE    "ONE", "TWO", "THREE"
          LISTTWO    "ONE", "TWO", "THREE"

i need to compare the whether the items in two lists are in same order or not.

Is there any way to do this in LINQ

Maybe:

bool equal = collection1.SequenceEqual(collection2);

See also: Comparing two collections for equality irrespective of the order of items in them

Determine if both lists contain the same data in same order:

bool result = list1.SequenceEqual(list2);

Same entries in different order:

bool result = list1.Intersect(list2).Count() == list1.Count;

If you know there can't be duplicates:

bool result = a.All(item => a.IndexOf(item) == b.IndexOf(item));

Otherwise

bool result = a.SequenceEquals(b)
List<string> list1;
List<string> list2;

bool sameOrder = list1.SequenceEqual(list2);

这些是正确的答案,但作为一个想法,如果你知道列表将具有相同的数据,但可能是不同的顺序,为什么不只是排序列表,以保证相同的顺序。

var newList = LISTONE.OrderBy(x=>x.[sequence]).ToList();

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